2014-04-03 106 views
1

我感覺這是一個簡單的修復,但我不能爲我的生活找到錯誤。當我運行此腳本檢查JSON文件中的數組以獲取布爾值數據時,我總是收到未定義的值。我把它全部放入小提琴中。滾動到JS部分的底部。以下是不想切換標籤頁的代碼。將JSON傳遞給循環

FIDDLE

$.ajax({ 
url: "/echo/json/", 
data: data, 
type: "POST", 
success: function (response) { 

    //Loop Start 
    for (var fund in response.fundClass){ 
     console.log(fund.class); 
     if(fund.xbrl == false){ 
      $(fund.class + " .xbrl").addClass(".hide"); 
     } 

     if(fund.prospSum == false){ 
      $(fund.class + " .prospSum").addClass(".hide"); 
     }    
    } 
    //Loop End 

    } 
}); 
+2

當你使用'for..in'時,你會得到*鍵*而不是數值。 'console.log(response.fundClass [fund] .class);'儘管由於'response.fundClass'是一個*數組*,所以我建議*不使用'for..in'。對於(var i = 0; i

+4

旁註:不要使用'class'作爲標識符,它的保留 – Satpal

回答

0

貌似response.fundClass是一個數組。所以for var in只是給鑰匙,嘗試平時for循環,而這是做了明確的方式,

for (var i =0 ; i < response.fundClass.length; i++){ 
    var fund = response.fundClass[i]; 
    console.log(fund.class); 
    if(fund.xbrl == false){ 
     $(fund.class + " .xbrl").addClass(".hide"); 
    } 

    if(fund.prospSum == false){ 
     $(fund.class + " .prospSum").addClass(".hide"); 
    }    
} 

希望這有助於!

+0

'for..in'將總是*給出鍵。不管它是一個數組還是一個對象。 –

+0

當然,同意了,發現了這個缺陷。更新我的回答 – aravind

0

當你使用一個for..in循環,你得到的不是值。 fund將是數組的關鍵,而不是它的值。

for (var key in response.fundClass){ 
    var fund = response.fundClass[key]; 
    console.log(fund['class']); 
} 

不過,因爲response.fundClass是一個數組,你不應該使用for..in。只需使用一個「正常」的for循環:

for(var i = 0; i < response.fundClass.length; i++){ 
    var fund = response.fundClass[i]; 
    console.log(fund['class']); 
} 
1

的問題是,你trating的「response.fundClass」爲對象,而它是一個數組。

Your fiddle updated

for (var i = 0; i < response.fundClass.length; i++) { // looping the Array 
    var fund = response.fundClass[i]; // get the object from the Array 
    console.log(fund.class); 
    if (fund.xbrl == false) { 
     $(fund.class + " .xbrl").addClass(".hide"); 
    } 

    if (fund.prospSum == false) { 
     $(fund.class + " .prospSum").addClass(".hide"); 
    } 
} 
+0

感謝您的回覆。我沒有意識到我的'for ... in'會返回鍵而不是數值。 – PStokes

0

作爲一種替代傳統的for(;;)循環(這是陣列枚舉的適當的傳統方法),是使用Arrays.forEach(墊片是廣泛可用的)。 forEach將枚舉所有項目陣列中的:

response.fundClass.forEach(function (fund) { 
    // Invoked once per each item, with fund being the value of the item. 

    // This is nice for several reasons, warranted or not here: 
    // 1. No explicit lookup by key/index or "extra" variables 
    // 2. Each loop is it's own execution context 
}); 

分配值只有項目列舉,但這是一個非問題從JSON恢復陣列。