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

发布了29 篇原创文章 · 获赞 4 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/mosakashaka/article/details/55190348