4.JavaScript-数据类型转换为布尔类型

1.将String类型转换为布尔类型

只要字符串中有内容(空格也算内容)都会转换为true,只有字符串中没有内容才会转换为false

// 有内容(空格也算内容)就会转换为true
let str = " ";
let bool = Boolean(str);
console.log(bool);  // true
console.log(typeof bool);  // boolean
// 没内容就会转换为false
let str = "";
let bool = Boolean(str);
console.log(bool);  // false
console.log(typeof bool);  // boolean

2.将Number类型转换为布尔类型

只有数值为0和NaN时才会转为false,其他的都会转为true

// 只有数值为0和NaN时才会转为false
let num = 0;
let num1 = NaN;
let bool = Boolean(num);
let bool1 = Boolean(num1);
console.log(bool);  // false
console.log(bool1);  // false
console.log(typeof bool);    // boolean
console.log(typeof bool1);    // boolean

3.将undefined类型转换为布尔类型

undefined会转换为false

let num = undefined;
let bool = Boolean(num);
console.log(bool);  // false
console.log(typeof bool);    // boolean

4.将null类型转换为布尔类型

null会转换为false

let num = null;
let bool = Boolean(num);
console.log(bool);  // false
console.log(typeof bool);    // boolean

\color{red}{总结:}

\color{red}{在JavaScript中如果想将基本数据类型转换为布尔类型, 那么只需调用Boolean(常量or变量)函数即可}
\color{red}{只有(空字符串/0/NaN/undefined/null) 会转换为false,其他的都会转换为true}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容