问题描述
我有一个对象(可以说是关联数组" - 也称为纯 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
上面的CS代码编译成JS:
bu the CS code above compiles to JS:
// JS
for (i = 0, len = obj.length; i < len; i++)
在这种情况下不合适.
JavaScript 方式是 for(var key in obj) 但现在我想知道:我如何在 CoffeeScript 中做到这一点?
The JavaScript way would be for(var key in obj) but now I'm wondering: how can I do this in CoffeeScript?
推荐答案
使用 for x,y of 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 age.这会添加一个检查以排除从原型继承的属性,这在本示例中可能不是问题,但如果您是在其他东西之上构建,则可能会出现问题.
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 中迭代对象中的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)