-1

Want to initialize array in Javascript with a name pattern like this:

var lineData0= [];
var lineData1= [];
var lineData2= [];
....

try to initialize the array like this:

for(var i=0; i<60; i++){
  var lineData+"i"= [];
}

Doesn't work? Is there any easy way?

2
  • possible duplicate of Dynamic variable name in loop Commented Apr 16, 2014 at 23:27
  • 1
    Whenever you have something like varnameX where X is a running number, you want an array instead. Commented Apr 16, 2014 at 23:28

2 Answers 2

1

Use an array of arrays instead:

var lineData = [];
for(var i = 0; i < 100; i++) {
    lineData.push([]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

In javascript, every object it's like a dictionary. You can do it this way:

var dictionary = {};

for(var i=0; i<60; i++){
  dictionary["lineData"+i]= [];
}

//set data
dictionary["lineData0"].push('hello');
dictionary["lineData1"].push('world');

//Print stuff
console.log(dictionary["lineData0"][0]);
console.log(dictionary["lineData1"][0]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.