javascript - TypeScript for 循环中数组中未定义的项目

标签 javascript arrays typescript angular

当我在某些 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/

相关文章:

浏览器中的 Typescript 转译与预编译 js 文件

generics - typescript 中的类型字典?

javascript - 用变量命名变量

java - 如何迭代列表以仅获取特定属性

PHP 获取数组中重复次数最多的项

Angular SVG 圆形进度条不适用于 Ionic

javascript - jquery中的选择器问题

Javascript、正则表达式 - 从头开始​​获取数字

php - 更改点击事件上的php变量

在c中创建动态数组