您的位置:首页 > Web前端 > JavaScript

4000 js 中双叹号(!!)的作用

2017-10-25 11:46 323 查看
双叹号( !! ) 一般用来将后面的表达式强制转换为布尔类型的数据,true / false。

因为js是弱类型的语言(变量没有固定的数据类型),所以有时需要强制转换为相应的类型,比如:

a = parseInt('3456'); //显示转换
b = someObject.toString(); //显示转换,将对象转换为字符串
c = "3456" + 0; //隐式转换,转换为数字
d = 3456 + ""; //隐式转换,转换为字符串

布尔类型的转换,js约定规则为:
false / undefinded / null / 0 / ""  ---> false

true / 1 / somestring / [object]   ---> true

对于 false / null 等值,用 !操作符时都会产生true的结果,所以  !!  的作用在于将这些值转换为 等价 的布尔值。

var foo;
console.log( !foo ); //true
console.log( !!foo ); //false
var o = {name: 'zyj'};
console.log( !o.name ); //false
console.log( !!o.name ); //true


所以,双叹号的作用在于如果变量的值为 null / undefined / 0 / ‘ ‘ 时,结果返回 false ;如果明确设置了变量的值,结果会根据变量的实际值来返回。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: