检查对象的所有属性是否未定义

时间:2015-03-30 21:30:22

标签: javascript object properties undefined

我试图单步执行一个对象以确保没有任何属性未定义。我找到了this questionthis question并实现了以下代码,但它不起作用。

for (var property in p.properties) {
    if (p.properties.hasOwnProperty(property)) {
        if (typeof property == 'undefined') {
            p.properties[property] = '';
            //a breakpoint here will NOT be hit
        }
    }
}

但是,如果我明确检查我所知道的具有未定义值的那个,它确实有效:

if(typeof p.properties.st == 'undefined') {
    p.properties.st = '';
    //a breakpoint here WILL be hit
}

以下是获取数据的方式:

$.getJSON("data/stuff.json", function (data) {
    $.each(data.features, function (i, p) {
       //checking for undefined properties here
    }
});

1 个答案:

答案 0 :(得分:4)

应该是:

if (typeof p.properties[property] == 'undefined')

您正在测试属性 name 是否未定义,这是不可能的;您想测试是否未定义。