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
- 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]
- Since accessing a property that doesn't exist and a property with value
gives you the same result, using theundefinedor equality operators is not enough to tell undefined properties apart from nonexistent ones. For that we can usetypeof, which returns true if the object has the property and false if it doesn't, orin, which does the same thing but doesn't look in the prototype chain.Object.hasOwnProperty()
备注说明,对象中的成员,可以直接用来访问,不用事先判断是否存在(但是对象要先存在)
摘自:
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

浙公网安备 33010602011771号