引用具有未知数组键的Javascript数组(JSON格式)

时间:2011-04-14 22:16:47

标签: javascript json

如果没有密钥,你如何在Javascript对象中引用一个值?

所以,给定对象:

var JSONdata= [ 
    {"index":"1","var1":1,"var2":2}, 
    {"index":"2","var1":3,"var2":2}, 
    {"index":"3","var1":3,"var2":1}, 
    {"index":"4","var1":2,"var2":1}, 
    {"index":"5","var1":1,"var2":3}, 
]; 

假设我想在循环中引用var1和var2的值,但名称“var1”和“var2”会发生变化,变量数也会发生变化。

所以在伪代码中:

while ( i < JSONdata.length ) {
   for (j = 1 to Num_variables) {
       Give me the value for varN
   next j
   }
i++
}

由于

2 个答案:

答案 0 :(得分:1)

JavaScript中的obj.propertyName符号是obj['propertyName']的语法糖 - 因此,您可以使用以下代码访问您的变量:JSONData[i]['var'+j];

答案 1 :(得分:1)

var JSONdata= [ 
  {"index":"1","var1":1,"var2":2}, 
  {"index":"2","var1":3,"var2":2}, 
  {"index":"3","var1":3,"var2":1}, 
  {"index":"4","var1":2,"var2":1}, 
  {"index":"5","var1":1,"var2":3}
]; 

var fields=[
  "var1",
  "var2"
];

for(var i=0, ii=JSONdata.length; i<ii; i++){
  for(var j=0, jj=fields.length; j<jj; j++){
    $('#hello').html($('#hello').html()+' '+JSONdata[i][fields[j]]);
  }
  $('#hello').html($('#hello').html()+' '+'<br/>');
}

看那里http://jsbin.com/ufege4/edit