将字符串转换为布尔值的四种方法:
- 使用Boolean构造函数
- 使用三元运算符检查字符串是否等于“true”
- 使用双感叹号!!运算符
- 使用 switch 语句
1、使用Boolean构造函数
const str = 'true'; const boolValue = Boolean(str); // boolValue is true
|
2、使用三元运算符检查字符串是否等于“true”。
const str = 'false'; const boolValue = str === 'false' ? true : false; console.log(boolValue);// boolValue is true
|
3、使用双感叹号!!运算符
const str = "false"; const boolValue = !!str; console.log(boolValue);
|
4、使用 switch 语句
const str:string = 'false'; let boolValue: boolean;
switch(str) { case 'true': boolValue = true; break; case 'false': boolValue = false; break; default: throw new Error('Invalid string value'); } console.log(boolValue);
|