JavaScript 的 for loop 到底发生了什么?

2019-08-03 03:17:09 +08:00
 ericgui

我有这么一段代码:


async getResultFromApi(){

   let result = [];	

   let resp = await requestApi();
   
   // console.log(resp.data)
   
   for (let item of resp.data){
   // console.log(item)
   	 -> result.push(item.x.y);
   }
   
   return result;
}

这段代码,console.log 可以看到所有信息,也就是说,每一个 item 都是{ x: { y: 'hello'}},但是,箭头这一行总报错,说找不到。cannot get y of null

而且 console.log(item)实在是打印不出来任何东西。。。。。

这简直是太无法理解了

所以请教大家,到底 for loop 发生了什么,console.log 又发生了什么?为什么可以 log 出来,但仍然报错?

真是快被郁闷死了。

2604 次点击
所在节点    程序员
11 条回复
heimeil
2019-08-03 03:22:10 +08:00
console.log(typeof item);
wunonglin
2019-08-03 03:47:59 +08:00
```
let result = []

try{
let resp = await requestApi()
for(const item of resp.data){
.....
}
}catch ( err ){
console.log(err)
}
```

err 值看看
dartabe
2019-08-03 04:05:21 +08:00
The operand of the of clause must be iterable. That means that you need a helper function if you want to iterate over plain objects
EugeneYWang
2019-08-03 04:56:46 +08:00
像楼上说的,你的 resp.data 不是 iterable
sker101
2019-08-03 05:48:14 +08:00
console.log(Object.assign({}, item) 试试
zqx
2019-08-03 08:25:53 +08:00
不能相信接口数据,要做个容错,这段代码把 y 去了,只 push item.x 肯定没问题
liuy1994g
2019-08-03 10:44:38 +08:00
item.x.y 着实属于高风险写法,这也是我越来越不喜欢 js 的原因
fool079
2019-08-03 10:59:31 +08:00
你可以 log 这个查看结果 Json.stringify(item)
不过一般这种情况一定要判空 比如 item && item.x && item.x.y
也可以用 lodash 的_.get
也可以用 js 新提案

不过到底还是接口的数据问题。
muzuiget
2019-08-03 14:33:26 +08:00
某个 item.x 是 null,最简单不就是“勾选出现异常时中断”吗?然后你就能查看出问题时那个 item 到时是什么。
lbunderway
2019-08-03 15:04:27 +08:00
typof item
lbunderway
2019-08-03 15:05:10 +08:00
typeof item

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/588687

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX