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
所以,双叹号的作用在于,如果变量的值为 null / undefined / 0 / ‘ ‘ 时,结果返回 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 ;如果明确设置了变量的值,结果会根据变量的实际值来返回。
相关文章推荐
- js中变量前两个叹号(!!)作用
- JS作用域详解 4000
- js中变量前两个叹号(!!)作用
- js 中 ~ 的作用
- JavaScript中双叹号(!!)作用
- 简述JS作用域、作用域链和闭包
- js变量以及其作用域详解
- js的执行环境及作用域
- 我的Node.js学习之路(三)--node.js作用、回调、同步和异步代码 以及事件循环
- JS高级程序设计笔记(二):变量、作用域和内存
- JavaScript的作用;JS常见的三种对话框;==和===的区别;函数内部参数数组arguments在函数内部打印实参;JS的误区:没有块级作用域
- angular js $scope 作用域
- js之变量和作用域
- JS作用域和ASP(vbs)作用域比较
- JS(数据类型、预解析、闭包、作用域、this)
- JS脚本defer的作用
- js私有作用域内调用函数外函数
- js 变量对象 作用域链
- js 作用域学习
- 关于JS里的函数作用域链的总结