javascript中的双感叹号语法(!!)

来源:互联网 发布:matlab 三维数组 画图 编辑:程序博客网 时间:2024/05/22 10:32
var o={flag1:true};  var test1=!!o.flag1;//等效于var test1=o.flag1||false;  console.log(test);//truevar test2=!!o.flag2;//等效于var test2=o.flag2||false;  console.log(test);//false 而不是undefined 或 null

由于对null与undefined用 !! 操作符时都会产生true的结果,
所以用两个感叹号的作用就在于,
如果设置了o中flag的值(非 null/undefined/0”“/等值),自然test就会取跟o.flag一样的值;
如果没有设置,test就会默认为false,而不是 null或undefined。

原创粉丝点击