当我在某些 REST 服务上设置匿名回调函数时,我遇到了一个非常奇怪的行为,如果我简单地 console.log
REST 服务的结果,我会得到预期的结果有效负载(对象数组)。但是,当我在同一个数组上运行循环并尝试获取某个键的值时,我收到错误,因为显然该项目是未定义
...
callback: (result) => {
console.log(result); // outputs [{text: 'foo'}, {text: 'bar'}]
for(let item of result){
console.log(item.text); // error can't read text of undefined
console.log(item); // HOWEVER... this works... :/
}
}
有什么想法吗?一定发生了某种异步行为,但我无法弄清楚。
谢谢!
最佳答案
您很可能有一个格式错误的数组。这是演示该问题的示例:
// Malformed array
const result = [
{text: 'foo'},
{text: 'bar'},
]
result.length = 3;
// Your code
console.log(result); // outputs [{text: 'foo'}, {text: 'bar'}]
for(let item of result){
console.log(item.text); // error can't read text of undefined
console.log(item); // HOWEVER... this works... :/
}
修复
- 过滤掉空项目。
更多提示
- console.log 将为不合理的内容打印一个空行。您可能在调试中没有看到这一点
- 阅读 JavaScript 数组漏洞
- 享受生活🌹
关于javascript - TypeScript for 循环中数组中未定义的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38240371/