5

JavaScript中两个感叹号(!!)的作用

 3 years ago
source link: https://blogread.cn/it/article/6125?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript中两个感叹号(!!)的作用

浏览:3333次  出处信息

看这么个例子:

var a;

var b=!!a;

a默认是undefined。!a是true,!!a则是false,所以b的值是false,而不再是undefined,也非其它值,主要是为后续判断提供便利。

!!一般用来将后面的表达式强制转换为布尔类型的数据(boolean),也就是只能是true或者false;
因为javascript是弱类型的语言(变量没有固定的数据类型)所以有时需要强制转换为相应的类型,类似的如:

  • a=parseInt(“1234″)

  • a=”1234″-0 //转换为数字

  • b=1234+”" //转换为字符串

  • c=someObject.toString() //将对象转换为字符串

其中第1种、第4种为显式转换,2、3为隐式转换

布尔型的转换,javascript约定规则为

  1. false、undefinded、null、0、”" 为 false

  2. true、1、”somestring”、[Object] 为 true

对null与undefined等其他用隐式转换的值,用!操作符时都会产生true的结果,所以用两个感叹号的作用就在于将这些值转换为“等价”的布尔值;

觉得文章有用?立即:

和朋友一起 共学习 共进步!

建议继续学习:

  1. JavaScript中双叹号(!!)作用    (阅读:1147)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK