等同于JavaScript isset() [英] JavaScript isset() equivalent
问题描述
在PHP中,您可以执行if(isset($array['foo'])) { ... }
.在JavaScript中,您经常使用if(array.foo) { ... }
来执行相同的操作,但这并不是完全相同的语句.如果array.foo
确实存在,但为false
或0
(也可能还有其他值),则条件也将评估为false.
In PHP you can do if(isset($array['foo'])) { ... }
. In JavaScript you often use if(array.foo) { ... }
to do the same, but this is not exactly the same statement. The condition will also evaluate to false if array.foo
does exists but is false
or 0
(and probably other values as well).
JavaScript中PHP isset
的完美替代品是什么?
What is the perfect equivalent of PHP's isset
in JavaScript?
从广义上讲,有关JavaScript处理不存在的变量,没有值的变量等的通用完整指南将很方便.
In a broader sense, a general, complete guide on JavaScript's handling of variables that don't exist, variables without a value, etc. would be convenient.
推荐答案
I generally use the typeof
operator:
if (typeof obj.foo !== 'undefined') {
// your code here
}
如果该属性不存在或其值为undefined
,它将返回"undefined"
.
It will return "undefined"
either if the property doesn't exist or its value is undefined
.
(另请参见: undefined
与未定义之间的区别.)
(See also: Difference between undefined
and not being defined.)
There are other ways to figure out if a property exists on an object, like the hasOwnProperty
method:
if (obj.hasOwnProperty('foo')) {
// your code here
}
和in
运算符:
if ('foo' in obj) {
// your code here
}
后两者的区别在于,hasOwnProperty
方法将检查对象上的属性是否物理存在(不继承).
The difference between the last two is that the hasOwnProperty
method will check if the property exist physically on the object (the property is not inherited).
in
运算符将检查原型链中所有可达的属性,例如:
The in
operator will check on all the properties reachable up in the prototype chain, e.g.:
var obj = { foo: 'bar'};
obj.hasOwnProperty('foo'); // true
obj.hasOwnProperty('toString'); // false
'toString' in obj; // true
如您所见,当检查toString
方法时,hasOwnProperty
返回false
,并且in
运算符返回true
,该方法在原型链中定义,因为obj
继承了形式Object.prototype
.
As you can see, hasOwnProperty
returns false
and the in
operator returns true
when checking the toString
method, this method is defined up in the prototype chain, because obj
inherits form Object.prototype
.
这篇关于等同于JavaScript isset()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!