推送到数组中的未定义索引

时间:2019-08-30 20:02:33

标签: javascript

是否有更好的方法将某些内容推入数组中的未定义索引,而不是此方法:

// 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"]];

我正在寻找推送到数组中未定义索引的地方。

所以我需要在索引中创建数组,然后执行push()。

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找的是这个

const array = [];

array[42] ='hello';

您只需分配一个值即可在数组的特定索引处设置一个值。

答案 1 :(得分:0)

您无需为此使用push,只需执行arr[index] = data

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

  

注意:如果您在最大索引上方分配了一个值,则索引之间的值将为undefined,请在上面的代码段中查找索引10