我正在尝试对对象字面量构造函数内部的 javascript 数组使用动态更新的访问器。数据和索引变量都在相同的功能范围内。
var data = [];
var index = 0;
dateKeys.forEach(element=>{
data.push({"date":element,[otherKeys[0]]:currentAccount[index]["2017_Q1"],[otherKeys[1]]:0,[otherKeys[2]]:0,[otherKeys[3]]:0,[otherKeys[4]]:0,[otherKeys[5]]:0})
index = index +1;
})
上面的代码产生以下错误消息:TypeError: undefined is not an object (evaluating 'currentAccount[index]["2017_Q1"]')
但是当我尝试时:
dateKeys.forEach(element=>{
var index = 0;
data.push({"date":element,[otherKeys[0]]:currentAccount[index] ["2017_Q1"],[otherKeys[1]]:0,[otherKeys[2]]:0,[otherKeys[3]]:0,[otherKeys[4]]:0,[otherKeys[5]]:0})
index = index +1;
})
我获得了索引 0 的正确数据,但它没有更新。为什么范围界定似乎对使用变量名称代替方括号中的数字的能力产生影响?我尝试过使用 let 来查看这是否是一个绑定(bind)问题,但这没有什么区别。有没有使用普通 JavaScript 的解决方案?
最佳答案
这是因为每次调用 forEach
回调时都会声明并初始化 index
变量。
例如,如果 dateKeys
有 5 个项目,则 element => ...
将被调用 5 次,每次都会创建一个新变量 index
并将其值设置为 0。
在第二种情况下,您永远不会使用 index
值 1 访问 currentAccount
。
您收到此错误是因为 dataKeys
的条目多于 currentAccount
。
关于javascript - 数组访问问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55553110/