Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/465.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 推送到数组中未定义的索引_Javascript - Fatal编程技术网

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

Javascript 推送到数组中未定义的索引,javascript,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) {

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

// 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"]];
//只是一个例子
让数组=[];
设indexInArray=0;
让data=“data”;
//这会引发错误
//数组[indexInArray].push(数据);

对于(设i=0;i我想你要找的是:

const array = [];

array[42] ='hello';

您可以在数组中的特定索引处设置一个值,只需将该值赋值即可。

我想您需要的是:

const array = [];

array[42] ='hello';

您只需为数组中的特定索引赋值即可设置该值。

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

const数组=[1,2,未定义];
常数数据='Neel';
数组[3]=数据;
数组[10]=数据;

console.log(array);
您不需要使用
push
为此,您只需要执行此操作
arr[index]=data

const数组=[1,2,未定义];
常数数据='Neel';
数组[3]=数据;
数组[10]=数据;


console.log(array);
你想用它实现什么?你想用它实现什么?对不起。我编辑了我的帖子。我需要在索引中推送数组。我想在总是检查索引中的数组是否未定义之前这样做。它不能推送该数组中的任何内容,在Javascript数组
[]
和对象
{}
这两个
typeof
都是
对象
,因此这里您将一个键值对
array[42]=“hello”
分配到一个数组中。即使您也可以这样做
array[-1]='-1'
@NeelRathod我在找这样的东西。但是我需要在
数组中的索引上做这件事,而不是在
数组中做这件事。看起来你想把
未定义的
数组元素转换成
索引
很抱歉。我编辑了我的帖子。我需要推送到索引中的数组。我想在总是检查索引中的数组是否未定义之前这样做。在Javascript数组
[]
和对象
{}中,它不能推送该数组中的任何内容
这两个
typeof
都是
对象
,因此这里您将一个键值对
array[42]=“hello”
分配到一个数组中。即使您也可以这样做
array[-1]='-1'
@NeelRathod我在找这样的东西。但是我需要在
数组中的索引上做这件事,而不是在
数组中做这件事。看起来你想把
未定义的
数组元素转换成
索引
很抱歉误解。请看我的帖子。这不是我的问题。我知道。但我想将一些数据推送到数组[index]。我需要数组[index]中的数组请把你的预期结果写下来。我已经不知道如何更好地解释它。谢谢你的时间!@JohnDoe很乐意帮忙。这个答案有什么问题吗?请评论、投票或确实接受答案。-抱歉误解。看看我的帖子。这不是我的问题。我知道。但我想推一些数据到数组[index]。我需要数组[index]中的数组并将其推入。请将您的预期输出完成。我已经不知道如何更好地解释它。谢谢您的时间!@JohnDoe乐于帮助。这个答案有什么问题吗?请评论、投票或确实接受答案