2014-04-03 105 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恢复阵列。