菜鸟提问 Javascript ~

2013-11-24 16:03:30 +08:00
 mopig
https://gist.github.com/mopig/7624625

提示 firstName undefined,实际 friends 里边的 i 是有 firstName 的。
3211 次点击
所在节点    JavaScript
10 条回复
aveline
2013-11-24 16:12:48 +08:00
用 friends[i]。
clippit
2013-11-24 16:13:21 +08:00
friends[i]
clippit
2013-11-24 16:14:23 +08:00
@aveline 啊被抢沙发了……
housne
2013-11-24 16:22:40 +08:00
. 只能访问到关键字,很明显这里的 i 是变量,要用 []
mopig
2013-11-24 16:27:24 +08:00
@aveline
@clippit
@housne 嗯,开始不清楚这两个的区别。感谢已发
dorentus
2013-11-24 17:17:20 +08:00
>> for(var i in friends)
>> 第一次循环时,i 的值是字符串 'bill'
>> friends.i 等价于 friends['i']
>> 而你想要的是 friends.bill,等价于 friends['bill']
mopig
2013-11-24 20:02:17 +08:00
@dorentus friends.bill, friends['bill'] 这个是等价的吧,只是在加载 i 的时候变成了:friends.'bill' ?
bombless
2013-11-24 21:52:53 +08:00
噗……楼主还是没习惯。

a.i 就是 a['i']

那你想,你要得到 friends.bill 那就应该是 friends['bill'] ,想得到 friends.i 就是 friends['i']
你写的是 friends.i ,等价于 friends['i'] ,它显然和 friends['bill'] 不是同一个东西。

完全不存在friends.'bill'这种东西。

这里也不存在“加载i的时候”怎么样了,因为 friends.i 永远都是 friends['i'] 不可能变成 friends['bill']
mopig
2013-11-24 22:21:06 +08:00
@bombless 茅塞顿开,非常感谢
xiezi
2013-11-25 22:01:29 +08:00
这个应该的错误信息是"Cannot read property 'firstName' of undefined",这说明friends.i是没有定义的,而不是你写的“firstName undefined”。@bombless写的很清楚了!

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

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

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

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

© 2021 V2EX