Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - 等同于JavaScript isset()(JavaScript isset() equivalent)

In PHP you can do if(isset($array['foo'])) { ... } .

(在PHP中,您可以执行if(isset($array['foo'])) { ... } 。)

In JavaScript you often use if(array.foo) { ... } to do the same, but this is not exactly the same statement.

(在JavaScript中,您经常使用if(array.foo) { ... }来执行相同的操作,但这并不完全相同。)

The condition will also evaluate to false if array.foo does exists but is false or 0 (and probably other values as well).

(如果array.foo确实存在,但条件为false0 (也可能还有其他值),则条件也将评估为false。)

What is the perfect equivalent of PHP's isset in JavaScript?

(什么是JavaScript中PHP的isset的完美isset ?)

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.

(从更广泛的意义上讲,有关JavaScript处理不存在的变量,没有值的变量等的通用完整指南将很方便。)

  ask by Bart van Heukelom translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I generally use the typeof operator:

(我通常使用typeof运算符:)

if (typeof obj.foo !== 'undefined') {
  // your code here
}

It will return "undefined" either if the property doesn't exist or its value is undefined .

(如果该属性不存在或其值是undefined ,它将返回"undefined" 。)

(See also: Difference between undefined and not being defined. )

((另请参见: undefinedundefined之间的区别。)

There are other ways to figure out if a property exists on an object, like the hasOwnProperty method:

(还有其他方法hasOwnProperty对象上是否存在属性,例如hasOwnProperty方法:)

if (obj.hasOwnProperty('foo')) {
  // your code here
}

And the in operator:

(和in运算符:)

if ('foo' in obj) {
  // your code here
}

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).

(最后两者之间的区别是, hasOwnProperty方法将检查属性的对象上实际存在(该财产不继承)。)

The in operator will check on all the properties reachable up in the prototype chain, eg:

(in运算符将检查原型链中所有可达的属性,例如:)

var obj = { foo: 'bar'};

obj.hasOwnProperty('foo'); // true
obj.hasOwnProperty('toString'); // false
'toString' in obj; // true

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 .

(如您所见,在检查toString方法时, hasOwnProperty返回falsein运算符返回true ,该方法在原型链中定义,因为obj继承了Object.prototype形式。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...