javascript - 在多个数组中复制一个对象数组

标签 javascript

我想将一个对象数组复制为多个对象,因为我需要在不同的地方使用它们中的每一个。

if(!this.tempLookups){
    for (let count = 0; count < this.dates.length; count++) {
       this.tempLookups[count] = this.lookups[key];
    }
}

错误:未捕获( promise )TypeError:无法设置 null 的属性“0”

最佳答案

错误的实际原因在错误消息中很清楚,您正在尝试将属性设置为 null。因此,为了修复,只需在 if 之后定义它。

if(!this.tempLookups){
    his.tempLookups = [];
    for (let count = 0; count < this.dates.length; count++) {
       this.tempLookups[count] = this.lookups[key];
    }
}

您可以使用 Array#fill 在没有 for 循环的情况下在一行中完成它方法,因为您正在填充相同的值。

if(!this.tempLookups){    
   this.tempLookups = new Array(this.dates.length).fill(this.lookups[key]);
} 

关于javascript - 在多个数组中复制一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59642026/

相关文章:

javascript - document.getElementById ("foo").innerHTML 打印 HTML 但不可见

javascript - 从隐藏的复选框中获取值(value)

javascript - 如何计算 JavaScript 测验的百分比分数?

javascript - 根据变量使 ng-click 调用某个方法

javascript - 将数据直接加载到选择框angularjs

javascript - Angular 2 - 如何将 id 属性设置为动态加载的组件

javascript - 如何使用 Jquery 或 Javascript 将 UTF-8 字母替换为类似的拉丁字母

javascript - d3.js 拖动节点边界不适用于链接路径

javascript - 触摸设备、单击和双击事件处理程序 jQuery/Javascript?

javascript - 缩短公会角色列表