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

Check all properties of object for undefined

本文关键字:属性 是否 未定义 对象 检查      更新时间:2023-09-26

我正在尝试遍历一个对象,以确保没有未定义的属性。我发现了这个问题和这个问题,并实现了以下代码,但它不起作用。

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
    }
});

应该是:

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

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