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 ...
$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
-
Why do you need 200 variables? Why not have one array with 200 elements?lonesomeday– lonesomeday2011年04月19日 14:10:07 +00:00Commented Apr 19, 2011 at 14:10
4 Answers 4
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 :-)
6 Comments
var msgs = []; line) outside of the "$(document).ready()" block. Second thing is that you will have to delay the dojo setup code that uses "msgs" until after the ajax call completes. Maybe put it in a function and call it from the ajax handler. (If it's not clear you should probably post a separate question about that part.)$msg = [];
for (var i=0; i<200; i++) {
$msg.push(parseFloat(json[i]["valor"+i]));
}
Comments
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.
1 Comment
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;