pan*_*nis 7 javascript typescript
我正在尝试将字符串转换为布尔值.有几种方法可以做到这一点
let input = "true";
let boolVar = (input === 'true');
Run Code Online (Sandbox Code Playgroud)
这里的问题是我必须验证输入是真还是假.而不是验证第一个输入然后进行转换是否有更优雅的方式?在.NET中bool.TryParse
,如果字符串无效,则返回false.打字稿中是否有相应的东西?
你可以做这样的事情,你可以有三种状态.undefined
表示该字符串不能解析为boolean:
function convertToBoolean(input: string): boolean | undefined {
try {
return JSON.parse(input);
}
catch (e) {
return undefined;
}
}
console.log(convertToBoolean("true")); // true
console.log(convertToBoolean("false")); // false
console.log(convertToBoolean("invalid")); // undefined
Run Code Online (Sandbox Code Playgroud)
返回true
, 1
, , '1'
(不区分大小写)。否则true
'true'
false
function primitiveToBoolean(value: string | number | boolean | null | undefined): boolean {
if (typeof value === 'string') {
return value.toLowerCase() === 'true' || !!+value; // here we parse to number first
}
return !!value;
}
Run Code Online (Sandbox Code Playgroud)
这是单元测试:
describe('primitiveToBoolean', () => {
it('should be true if its 1 / "1" or "true"', () => {
expect(primitiveToBoolean(1)).toBe(true);
expect(primitiveToBoolean('1')).toBe(true);
expect(primitiveToBoolean('true')).toBe(true);
});
it('should be false if its 0 / "0" or "false"', () => {
expect(primitiveToBoolean(0)).toBe(false);
expect(primitiveToBoolean('0')).toBe(false);
expect(primitiveToBoolean('false')).toBe(false);
});
it('should be false if its null or undefined', () => {
expect(primitiveToBoolean(null)).toBe(false);
expect(primitiveToBoolean(undefined)).toBe(false);
});
it('should pass through booleans - useful for undefined checks', () => {
expect(primitiveToBoolean(true)).toBe(true);
expect(primitiveToBoolean(false)).toBe(false);
});
it('should be case insensitive', () => {
expect(primitiveToBoolean('true')).toBe(true);
expect(primitiveToBoolean('True')).toBe(true);
expect(primitiveToBoolean('TRUE')).toBe(true);
});
});
Run Code Online (Sandbox Code Playgroud)
您还可以使用有效值数组:
const toBoolean = (value: string | number | boolean): boolean =>
[true, 'true', 'True', 'TRUE', '1', 1].includes(value);
Run Code Online (Sandbox Code Playgroud)
或者您可以使用 switch 语句,就像在类似的 SO 问题的答案中所做的那样。
MG8*_*G83 -5
我建议您希望 boolVar 对于输入等于 true 且输入等于“true”(与 false 相同)为 true,否则它应该为 false。
let input = readSomeInput(); // true,"true",false,"false", {}, ...
let boolVar = makeBoolWhateverItIs(input);
function makeBoolWhateverItIs(input) {
if (typeof input == "boolean") {
return input;
} else if typeof input == "string" {
return input == "true";
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19680 次 |
最近记录: |