1

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']
]

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, that solved my problem! Can you explain why it is reporting that error? I mean what's wrong with my code?
@DipendraGurung The .push() method will automatically append the items to the end of the array. On each iteration, you were trying to access a value that didn't exist in the array. See the update.
You are trying to access 'items[i]' which is undefined as array is empty.

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.