2015-03-30 41 views
3

我試圖通過一個對象來確保沒有任何屬性是未定義的。我發現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 
    } 
}); 
+0

您正在檢查它是否爲'undefined'作爲字符串。丟失引號:'undefined' – mcranston18 2015-03-30 21:35:17

+0

我不認爲這是正確的...... – 2015-03-30 21:35:44

+0

@ mcranston18'typeof'總是返回一個字符串。 – Barmar 2015-03-30 21:36:25

回答

4

它應該成爲:

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

You'r e測試屬性名稱是否未定義,這是不可能的;您要測試是否未定義。

+3

/facepalm。謝謝。 – 2015-03-30 21:38:12

+0

嗯,當我嘗試p.properties.st.toLowerCase() – 2015-03-30 21:41:27

+0

我仍然得到「無法讀取屬性」toLowerCase的未定義「我不認爲JSON會創建具有未定義值的屬性。該屬性可能根本不存在。 – Barmar 2015-03-30 21:43:18

相關問題