loop with array data
i have this code to get three values.
success: function(json){
$msg1 = parseFloat(json[0].valor1);
$msg2 = parseFloat(json[1].valor2);
$msg3 = parseFloat(json[2].valor3);
}
but now suppose that i need 200 values. I'm not doing 200 times ...
开发者_StackOverflow $msg1 = parseFloat(json[0].valor1);
$msg2 = parseFloat(json[1].valor2);
$msg3 = parseFloat(json[2].valor3);
//...
$msg200 = parseFloat(json[199].valor200);
so, i need a loop, correct?
i tried something like this
for (i=0; i<200; i++) {
$msg(i+1) = parseFloat(json[i].valor(i+1));
i++;
}
but didn't work
thanks
This is why The Creator gave the world arrays.
var msgs = [];
for (var i = 0; i < 200; ++i)
msgs.push(parseFloat(json[i]['valor' + i]));
Note that your JSON data should also keep those "valor" properties as arrays, though in JavaScript you can deal with a bizarre naming scheme like that as in the example above.
edit — oops, typos fixed :-)
$msg = [];
for (var i=0; i<200; i++) {
$msg.push(parseFloat(json[i]["valor"+i]));
}
As stated by Pointy or:
var msgs = [];
for (i=0; i<200; i++) {
$msg[i] = parseFloat(eval('json[' + i + '].valor(' + i + '+1)'));
i++;
}
However eval is slow, so Pointy's answer is better.
var array = json.someid;// or json['someid'];
// json is returned not an array
var msgs = [];
$.each(array, function(index, e) {
msgs.push(parseFloat[e['valor' + index], 10);
});
when using parseFloat use the radix parameter unless you want bad things to happen;
javascript needs to be told for example not to parse octal;
精彩评论