Dipendra Gurung
Dipendra Gurung

Reputation: 5870

javascript array format via for loop

What I am doing wrong here? I am getting TypeError: items[i] is undefined as the error.

var items = [];
for(var i = 1; i <= 3; i++){
    items[i].push('a', 'b', 'c');
}
console.log(items);

I need an output as given below,

[
    ['a', 'b', 'c'],
    ['a', 'b', 'c'],
    ['a', 'b', 'c']
]

Upvotes: 1

Views: 43

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240888

You could simply use the following:

items.push(['a', 'b', 'c']);

No need to access the array using the index, just push another array in.

The .push() method will automatically add it to the end of the array.

var items = [];
for(var i = 1; i <= 3; i++){
    items.push(['a', 'b', 'c']);
}
console.log(items);

As a side note, it's worth pointing out that the following would have worked:

var items = [];
for(var i = 1; i <= 3; i++){
    items[i] = []; // Define the array so that you aren't pushing to an undefined object.
    items[i].push('a', 'b', 'c');
}
console.log(items);

Upvotes: 1

Related Questions