等同于JavaScript isset() [英] JavaScript isset() equivalent

查看:106
本文介绍了等同于JavaScript isset()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,您可以执行if(isset($array['foo'])) { ... }.在JavaScript中,您经常使用if(array.foo) { ... }来执行相同的操作,但这并不是完全相同的语句.如果array.foo确实存在,但为false0(也可能还有其他值),则条件也将评估为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆