简体   繁体   中英

Push to undefined index in array

Is there any better way to push something to undefined index in array instead of this:

// Just an example

let array = [];
let indexInArray = 0;
let data = "data";

// This throws error
// array[indexInArray].push(data);

for(let i = 0; i <= 1; i++) {
    if(array[indexInArray] == undefined) {
        array[indexInArray] = [data];
    } else {
       // This throws error if i = 0
       array[indexInArray].push(data);
    }
}

// array = [["data", "data"]];

I am looking for pushing to undefined index in array.

So I need to create array in index and then do push().

I think what you're looking for is this:

const array = [];

array[42] ='hello';

You can set a value at a specific index in an array simply by assigning to that value.

You don't need to use push for that, you just need to do this arr[index] = data

 const array = [1, 2, undefined]; const data = 'Neel'; array[3] = data; array[10] = data; console.log(array); 

Note : If you assign a value on above max index then a value of between index will be undefined , Check above snippet for index 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM