首页 > 解决方案 > 向数组js添加数据,当数组为空时,数据到n位置

问题描述

早上好,我正在尝试将值附加到在全局范围内声明的空数组。该数组将保存枚举结果的值,放置在索引给定的相同位置,如下所示:

array[index] += result

因此,当数组为空并且我以这种方式分配时,在 chrome 控制台中给我这个:

(2) [empty, NaN]

然后,如果我将该结果存储为全局变量并在此处复制粘贴,它将为我们提供以下信息:

[
  null,
  null
]

我之前尝试的是这样的:

 if (array[index] == undefined) {
            //first try
            array[index] += result;
            //if 'empty'(better null?) put 0 for now
            array.forEach(x => x == "empty" ? x = 0 : x = result)
            //second try
            array.splice(index, index(plus 1?), result);
}

因为我想要的是这样的:

“使用空数组在 n 位置附加数据(位置 < n 位置),值 = 0”

你怎么看待这件事?

非常感谢你,

七客

标签: javascriptarrays

解决方案


希望它会起作用

//here is new Array N terms

    var newArray = Array.apply(null,Array(25)).map(a=>null) 

    //newArray[index] = append value

    newArray[2] = 'Hello_1'
    newArray[5] = 'Hello_2'
    newArray[7] = 'Hello_3'
    newArray[11] = 'Hello_4'

    console.log('Append',newArray,'or other show null')


推荐阅读