anson920520 anson920520 - 1 year ago 76
Javascript Question

Javascript : Store data in variables by for loop

I am having some random JSON data at the moment, therefore I cannot using standrad way to do it, cannot do it one by one.

For example if i am going to store specific data as array i will do something like below

var tester = []; // store their names within a local array

for(var k = 0; i < data.result.length; i++){ //maybe 6

for(var i = 0; i <; i++){ //maybe 30 times in total



But since I cannot predict how many set of data i have i can't really do something like

var tester = [];
var tester2 = [];
var tester3 = [];
var tester4 = [];

for(var i = 0; i <; i++){ //maybe 30 times in total



if there' any better way which using for loop to store these data?

Answer Source

Make tester a 2-dimensional array and use nested loops.

var tester = [];

for (var i = 0; i < data.result.length; i++) {
    var curTester = [];
    var result = data.result[i];
    for (var j = 0; j <; j++) {

Some general principles:

  1. Any time you find yourself defining variables with numeric suffixes, they should probably be an array.
  2. When you don't know how many of something you're going to have, put them in an array.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download