How would you reference a value in a Javascript object without the key?
So, given the object:
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},
];
Say I want to reference the values of var1 and var2 in a loop, but the names "var1" and "var2" change and the number of variables also changes.
So in Pseudocode:
while ( i < JSONdata.leng开发者_运维技巧th ) {
for (j = 1 to Num_variables) {
Give me the value for varN
next j
}
i++
}
Thanks
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/>');
}
see there http://jsbin.com/ufege4/edit
The obj.propertyName
notation in JavaScript is syntactic sugar for obj['propertyName']
-- So, you can access your vars using: JSONData[i]['var'+j];
精彩评论