如何检查JavaScript中的对象属性是否未定义?


当前回答

Object.hasOwnProperty(o,'propertyname');

然而,这并不能通过原型链进行查找。

其他回答

查看注释,对于那些想同时检查两者的人来说,它是未定义的还是其值为空:

//Just in JavaScript
var s; // Undefined
if (typeof s == "undefined" || s === null){
    alert('either it is undefined or value is null')
}

如果您使用的是jQueryLibrary,那么jQuery.isEmptyObject()将足以满足这两种情况,

var s; // Undefined
jQuery.isEmptyObject(s); // Will return true;

s = null; // Defined as null
jQuery.isEmptyObject(s); // Will return true;

//Usage
if (jQuery.isEmptyObject(s)) {
    alert('Either variable:s is undefined or its value is null');
} else {
     alert('variable:s has value ' + s);
}

s = 'something'; // Defined with some value
jQuery.isEmptyObject(s); // Will return false;
if ( typeof( something ) == "undefined") 

这对我有用,而其他人没有。

在JavaScript中,有truthy和falsy表达式。如果要检查属性是否未定义,可以直接使用给定的If条件,

使用真/假概念。

if(!ob.someProp){
    console.log('someProp is falsy')
}

然而,还有几种方法可以检查对象是否具有属性,但对我来说似乎很长。

使用==未定义的签入if条件

if(ob.someProp === undefined){
    console.log('someProp is undefined')
}

使用的类型

typeof充当未定义值和变量是否存在的组合检查。

if(typeof ob.someProp === 'undefined'){
    console.log('someProp is undefined')
}

使用hasOwnProperty方法

JavaScript对象已在对象原型中的hasOwnProperty函数中构建。

if(!ob.hasOwnProperty('someProp')){
    console.log('someProp is undefined')
}

不深入,但第一种方法看起来很短,对我来说很好。下面是JavaScript中truthy/falsy值的详细信息,未定义的是其中列出的falsy。所以if条件的行为正常,没有任何故障。除了未定义的值之外,值NaN、false(显然)、“”(空字符串)和数字0也是假值。

警告:请确保属性值不包含任何错误值,否则if条件将返回false。对于这种情况,可以使用hasOwnProperty方法

function isUnset(inp) {
  return (typeof inp === 'undefined')
}

如果变量已设置,则返回false;如果未定义,则返回true。

然后使用:

if (isUnset(var)) {
  // initialize variable here
}

我不确定将==与typeof一起使用的起源,按照惯例,我在许多库中都使用了它,但typeof运算符返回字符串文本,我们事先就知道了,所以为什么还要对其进行类型检查呢?

typeof x;                      // some string literal "string", "object", "undefined"
if (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") {    // sufficient