在 JavaScript 中,如果你有一个字符串 'true'
2024-05-06 本文已影响0人
林希品
在 JavaScript 中,如果你有一个字符串 'true' 并希望将其转换为布尔值 true,可以使用双重否定运算符 (!!) 或 Boolean 函数进行转换:
let str = 'true';
// 使用双重否定运算符
let boolValue = !!str;
// 或者使用 Boolean 函数
let boolValueUsingFunction = Boolean(str);
console.log(boolValue); // 输出: true
console.log(boolValueUsingFunction); // 输出: true
这两种方法都会把非空字符串(包括 'true')转换为 true,空字符串('')转换为 false。在JavaScript中,除了undefined、null、false、NaN、0、""(空字符串)之外,其余所有的值(包括任何非空字符串)转换为布尔值时都是 true。所以,无论你有一个 'true' 还是 'anyNonEmptyString' 字符串,转换后的布尔值都是 true。