1

Can you please let me know if it is possible to create dynamically sets of arrays in JS? I tried some thing like this but didn't work

for (i = 0; i < 3; i++) { 
    var item[i] = [];
}
item1.push(1);
console.log(item1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

3
  • Dynamic array and Dynamic variables are different. Multidimensional array will be the solution for your problem.. You can not create dynamic variables Commented Sep 27, 2015 at 3:52
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 27, 2015 at 3:54
  • I don't quite get what you are trying to achieve, are you creating dynamic 2D arrays? Commented Sep 27, 2015 at 3:59

1 Answer 1

4

You're almost there. Assuming you're trying to create a two dimensional array (an array of arrays), you just have to declare the top level array and then reference the first level array with [x] array syntax like this:

var items = [];
for (i = 0; i < 3; i++) { 
    items[i] = [];
}

// Here items is an array of arrays where each first level array entry
// is an empty array.  You can then put things into those empty arrays

// You can reference the first level array here
items[1].push(1);
items[1].push(2);
console.log(items[1]);    // [1,2]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks jfriend00, this is exactly what I am looking for

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.