布尔类型转换
布尔类型只有两个值:true和false。任何直观上为空的都被转换为false,其他的转换为true。
显示转换为布尔类型时,使用Boolean(Value)函数。
布尔类型转换规则
类型 | 类型转换后 |
0 | false |
“0” | true |
“ ” 或者 ‘ ’ | true |
“” 或者 ‘’ 即空字符串 | false |
null | false |
undefined | false |
NaN | false |
|
|
例子:
let val1 = ' ';
let val2 = " ";
let val3 = '0';
let val4 = 0;
let val5 = null;
let val6 = undefined;
let val7 = NaN;
let val8 = 'hello'
console.log('val1:',typeof val1)
console.log(Boolean(val1))
console.log(typeof Boolean(val1))
console.log('val2:',typeof val2)
console.log(Boolean(val2))
console.log(typeof Boolean(val2))
console.log('val3:',typeof val3)
console.log(Boolean(val3))
console.log(typeof Boolean(val3))
console.log('val4:',typeof val4)
console.log(Boolean(val4))
console.log(typeof Boolean(val4))
console.log('val5:',typeof val5)
console.log(Boolean(val5))
console.log(typeof Boolean(val5))
console.log('val6:',typeof val6)
console.log(Boolean(val6))
console.log(typeof Boolean(val6))
console.log('val7:',typeof val7)
console.log(Boolean(val7))
console.log(typeof Boolean(val7))
console.log('val8:',typeof val8)
console.log(Boolean(val8))
console.log(typeof Boolean(val8))
结果:
标签:类型转换,console,log,val8,JavaScript,Boolean,let,typeof,布尔 From: https://blog.51cto.com/u_16830897/12099947