js !!()

最近看书在JavaScript高级程序设计的能力检测中看到多处使用了 !!()

如:

var hasDOM1 = !!(document.getElementById && document.createElement && document.getElementsByTagName);

 

查了这个的用意,  看到一个比较好的答案 https://segmentfault.com/q/1010000006037616, 做个记录

用意是强制转为布尔型

 

还看到其它类似的转化

// 强制转换为Boolean 用 !!
var bool = !!"c";
console.log(typeof bool); // boolean

// 强制转换为Number 用 +
var num = +"1234";
console.log(typeof num); // number

// 强制转换为String 用 ""+
var str = ""+ 1234;
console.log(typeof str); // string

 

posted @ 2018-05-29 14:13  浮沫  阅读(265)  评论(0编辑  收藏  举报