如何在CoffeeScript中迭代对象中的键和值? [英] How to iterate over the keys and values in an object in CoffeeScript?

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

问题描述

我有一个对象(一个关联数组,也就是说 - 也称为普通的JavaScript对象):

I have an object (an "associate array" so to say - also known as a plain JavaScript object):

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

我想使用CoffeeScript迭代 obj ,如下所示:

I want to iterate over obj using CoffeeScript as follows:

# CS
for elem in obj

bu上面的CS代码编译成JS:

bu the CS code above compiles to JS:

// JS
for (i = 0, len = obj.length; i < len; i++)

在这种情况下是不合适的。

which isn't appropriate in this case.

对于(obj中的var键),JavaScript的方式是,但现在我'我想知道:我怎么能在CoffeeScript中做到这一点?

The JavaScript way would be for(var key in obj) 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在评论中提到的变种为自己的k,v 。这会添加一个检查来排除从原型继承的属性,这可能不是本例中的问题,但可能是在构建其他东西之上。

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中迭代对象中的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆