本文介绍了迭代在coffeescript中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象(一个关联数组,也称为一个简单的Javascript对象):

I have an object (an "associate array", also known as a plain Javascript object):

obj = {}
obj["Foo"] = "Bar"
obj["bar"] = "Foo"

我需要使用coffeescript迭代它。现在,这样做:

and I need to iterate over it using coffeescript. Now, doing like this:

for elem in obj

不工作,因为obj.length为0,编译js代码使用。在普通的Javascript中,我只需要做

does not work because obj.length is 0, which the compile js code uses. In normal Javascript I would just do

for(var key in obj)

但现在我想知道:我怎么能在coffeescript中这样做?

but now I'm wondering: how can I do this in coffeescript?

推荐答案

使用为x,y的L 。 。

ages = {}
ages["jim"] = 12
ages["john"] = 7

for k,v of ages
  console.log k + " is " + v

输出

jim is 12
john is 7

想要考虑Aaron Dufour在评论中提到的变量 for own k,v of ages 。这增加了一个检查来排除从原型继承的属性,这在这个例子中可能不是一个问题,但是如果你正在建立在其他东西之上。

You may also want to consider the variant for own k,v of ages as mentioned by Aaron Dufour in the comments. This adds a check to exclude properties inherited from the prototype, which is probably not an issue in this example but may be if you are building on top of other stuff.

这篇关于迭代在coffeescript中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 10:56