Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

javascript - How to iterate over the keys and values in an object in CoffeeScript?

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

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

I want to iterate over obj using CoffeeScript as follows:

# CS
for elem in obj

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.


The JavaScript way would be for(var key in obj) but now I'm wondering: how can I do this in CoffeeScript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use for x,y of L. Relevant documentation.

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

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

Outputs

jim is 12
john is 7

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...