【JS】自动转换布尔值的转换规则
淩度奢望 ✦ 暂无邮箱
var a="undefined", b="false", c="null", d="",e="0";
var f=undefined,g=false,h=null,i=0;
function assert(x) {
if (x) {
console.log("true");
}
else{
console.log("false");
}
}
console.log(assert(a));//true
console.log(assert(b));//true
console.log(assert(c));//true
console.log(assert(d));//false
console.log(assert(e));//true
console.log(assert(f));//false
console.log(assert(g));//false
console.log(assert(h));//false
console.log(assert(i));//false
console.log(assert(j));//false

if(condition)的condition求值结果若非布尔值,ECMAScript会自动调用Boolean()转换函数将结果转换为布尔值。转换规则为:

数据类型转换为true转换为false
booleantruefalse
String任何非空字符串空字符串
Number任何非零数字值0和NaN
Object任何对象null
Undefinedn/aundefined
Submit
no comments yet~