2014-01-28 17 views
0

試圖運行下面的代碼通過JSON對象循環檢查鍵值

var superGroup = $.parseJSON(data); 
$.each(superGroup, function(idx, obj) { 
      if (idx.contains("Addr_Line")) { 
       if (obj != null) { 
        currentAddress.push(obj); 
       } 
      } 
     }); 

哪裏超羣是一堆屬性的JSON對象,我基本上只需要添加在此對象的屬性的值,這包含「addr_line」。在Chrome中,我注意到有上

idx.contains() 

說IDX不包含方法包含

任何想法,我怎樣才能解決這個JS錯誤?

+1

在這種情況下,'idx'將是一個字符串或一個數字。它們都沒有'.contains()'方法。 **編輯**:['String.contains()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains)存在,但沒有任何內容(除Firefox)支持它。 –

+0

當我做了一個警報(idx),它顯示了我的對象的所有屬性名稱,例如id,blah,Address_Line_1,Address_Line_2等代碼似乎在Firefox中工作,但鉻不喜歡它 – StevieB

+0

您可以輕鬆地自己回答這個問題通過[閱讀文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains#Browser_compatibility)。 – Blazemonger

回答

1

根據the docs for String.contains,您可以通過添加以下代碼來填充此僅限Firefox的方法:

if (!('contains' in String.prototype)) { 
    String.prototype.contains = function(str, startIndex) { 
    return -1 !== String.prototype.indexOf.call(this, str, startIndex); 
    }; 
} 
2

這是因爲String.prototype.contains()不支持在Chrome:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains

只是這樣做:

$.each(superGroup, function(idx, obj) { 
    if (idx.indexOf('Addr_Line') !== -1) { 
     if (obj != null) { 
      currentAddress.push(obj); 
     } 
    } 
}); 

您可能還需要檢查是否idxstring

$.each(superGroup, function(idx, obj) { 
    if (typeof idx == 'string' && idx.indexOf('Addr_Line') !== -1) { 
     if (obj != null) { 
      currentAddress.push(obj); 
     } 
    } 
}); 
+0

是的,看到了現在..感謝很多! – StevieB