javascript中2个感叹号的用法实例详解
这篇文章主要介绍了javascript中2个感叹号的用法,并用大量的实例讲述了!!的常见应用情况,是非常实用的技巧,需要的朋友可以参考下
在javascript代码中经常会见到!!的情况,本文即以实例形式较为深入的分析javascript中2个感叹号的用法。分享给大家供大家参考之用。具体分析如下:
javascript中的!!是逻辑"非非",即是在逻辑“非”的基础上再"非"一次。通过!或!!可以将很多类型转换成bool类型,再做其它判断。
一、应用场景:判断一个对象是否存在
假设有这样一个json对象:
[code]{ color: "#E3E3E3", "font-weight": "bold" }[/code]
需要判断是否存在,用!!再好不过。
如果仅仅打印对象,无法判断是否存在:
[code]var temp = { color: "#A60000", "font-weight": "bold" }; alert(temp); [/code]
结果:[object: Object]
如果对json对象实施!或!!,就可以判断该json对象是否存在:
[code]var temp = { color: "#A60000", "font-weight": "bold" }; alert(!temp); [/code]
结果:false
[code]var temp = { color: "#A60000", "font-weight": "bold" }; alert(!!temp); [/code]
结果:true
二、通过!或!!把各种类型转换成bool类型的惯例
1.对null的"非"返回true
[code]var temp = null; alert(temp); [/code]
结果:null
[code]var temp = null; alert(!temp); [/code]
结果:true
[code]var temp = null; alert(!!temp); [/code]
结果:false
2.对undefined的"非"返回true
[code]var temp; alert(temp); [/code]
结果:undefined
[code]var temp; alert(!temp); [/code]
结果:true
[code]var temp; alert(!!temp); [/code]
结果:false
3.对空字符串的"非"返回true
[code]var temp=""; alert(temp); [/code]
结果:空
[code]var temp=""; alert(!temp); [/code]
结果:true
[code]var temp=""; alert(!!temp); [/code]
结果:false
4.对非零整型的"非"返回false
[code]var temp=1; alert(temp); [/code]
结果:1
[code]var temp=1; alert(!temp); [/code]
结果:false
[code]var temp=1; alert(!!temp); [/code]
结果:true
5.对0的"非"返回true
[code]var temp = 0; alert(temp); [/code]
结果:0
[code]var temp = 0; alert(!temp); [/code]
结果:true
[code]var temp = 0; alert(!!temp); [/code]
结果:false
6.对字符串的"非"返回false
[code]var temp="ab"; alert(temp); [/code]
结果:ab
[code]var temp="ab"; alert(!temp); [/code]
结果:false
[code]var temp="ab"; alert(!!temp); [/code]
结果:true
7.对数组的"非"返回false
[code]var temp=[1,2]; alert(temp); [/code]
结果:1,2
[code]var temp=[1,2]; alert(!temp); [/code]
结果:false
[code]var temp=[1,2]; alert(!!temp); [/code]
结果:true
相信本文所述对大家的javascript程序设计的学习有一定的借鉴价值。
经验分享互联网动态
更多阅读推荐