javascript - 向数组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”
你怎么看待这件事?
非常感谢你,
七客
解决方案
希望它会起作用
//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')
推荐阅读
- javascript - *ng-if 不在 ionic 5 中的 ion-modal 内部工作
- wpf - 图像、按钮或切换按钮不会显示在任何笔记本电脑上
- node.js - 运行节点应用程序时带有环境变量的 Docker CMD
- haskell - 如何在 Hakyll html 中为第二个帖子目录创建第二个列表?
- css - 为什么在尝试将我的 Angular 项目从基于 CSS 的项目转换为 SCSS 项目时出现此错误?
- django - 为前端图片渲染创建一个“虚拟”URL 路径
- postgresql - 按日期划分的范围分区,其中一个分区用于 NULL 日期
- directus - 如果将“多对多”字段添加到 directus_users
- javascript - 如何对齐 HTML5 表单验证气泡消息?
- vue.js - 使用组件通过 CDN 读取条码