I want to create array once and then just push values to it with any index , but i get Cannot read property 'push' of undefined
error
I have following scenario
JavaScript
x
2
1
var neg = [];
2
I want to use push randomly with any index
JavaScript
1
2
1
neg[0].push([1,2]);
2
or
JavaScript
1
2
1
neg[22].push([1,2]);
2
right now I want to define manually like neg[0] = [];
, Is there any one way where i can just push to any index i want ?
Advertisement
Answer
Here’s a quick way to do exactly what you want.
JavaScript
1
5
1
var arr = [];
2
3
(arr[0]=[]).push([1,2]);
4
5
console.log(arr)
Also it’s safer to check if an array already exists at this index, otherwise it will be replaced with an empty array – the above code will replace the array with an empty one if it already exists.
JavaScript
1
5
1
// creates an array at index 0 only if there's no array at this index.
2
// pushes an array of [1, 2] to the existing array at 0 index
3
// or the newly created empty one.
4
(arr[0] || (arr[0] = [])).push([1, 2]);;
5
JavaScript
1
7
1
var arr = [];
2
3
arr[0] = [1];
4
5
(arr[0]||(arr[0]=[])).push(2,3);
6
7
console.log(arr)