对对象属性的理解打回来
起初我对以下代码发生的情况有点困惑:
people =
jim: 'Jim'
james: 'James'
for k, v of people
setTimeout( ( -> console.log(k) ), 300 )
#OUTPUT
#james
#james
JavaScript 版本:
var people = {
jim: 'Jim',
james: 'James'
};
for(var k in people){
setTimeout( function(){ console.log(k); }, 300 );
};
//OUTPUT
//james
//james
但我猜当 console.log(k) 执行时 k 已经改变了?如何修复它以使输出为“jim, james”?
At first I was a little confused about what was happening with the following code:
people =
jim: 'Jim'
james: 'James'
for k, v of people
setTimeout( ( -> console.log(k) ), 300 )
#OUTPUT
#james
#james
JavaScript version:
var people = {
jim: 'Jim',
james: 'James'
};
for(var k in people){
setTimeout( function(){ console.log(k); }, 300 );
};
//OUTPUT
//james
//james
But I guess by the time console.log(k) gets executed k has already changed? How do you fix it so the output is "jim, james"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您遇到了经典的 JavaScript 闭包问题。请参阅 CoffeeScript 文档 的“循环和推导式”部分中有关“闭包包装器”的部分。
CoffeeScript 解决您问题的方法是使用
do
关键字:由于您包含了问题的 Javascript 版本,因此 Javascript 解决方案将如下所示:
但这是丑陋的罪过,所以我更喜欢这种方法,如果我用JS来做:
You are running into classic JavaScript closure issues. See the section about "closure wrappers" in the "Loops and Comprehensions" section of the CoffeeScript documentation.
The CoffeeScript solution to your problem is the
do
keyword:Since you included the Javascript version of the problem, the Javascript solution would be like this:
But this is ugly as sin, so I prefer this approach if I were to do it in JS: