Javascript 对象值与null undefined和空字符串

if (value) 是否足以判断一个值存在且不为空字符串?

答案是 是的。

 

 

if ((fields === null) || (fields === undefined) || (fields.length === 0)) {
 ...                    
}

 

 

if( value ) {
}

是等价的。

 

 

备注1:

 

if( value ) {
}

 

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

备注2:

 

  1. For objects, accessing a property that hasn't been attached will return undefined. You might see an error raised if you try to do something with it, like calling it as a method, but just accessing it is usually fine as long as the object itself exists. [2]
  2. Since accessing a property that doesn't exist and a property with value undefinedgives you the same result, using the typeof or equality operators is not enough to tell undefined properties apart from nonexistent ones. For that we can use in, which returns true if the object has the property and false if it doesn't, or Object.hasOwnProperty(), which does the same thing but doesn't look in the prototype chain.
备注说明,对象中的成员,可以直接用来访问,不用事先判断是否存在(但是对象要先存在)
 
 
摘自:
http://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in
https://www.quora.com/What-is-the-best-way-to-check-if-a-property-or-variable-is-undefined
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值