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
1.1k views
in Technique[技术] by (71.8m points)

javascript - Multiple conditions in for loop

How can I write a for loop with multiple conditions?

Intended Javascript:

for(k=1; k < 120 && myThing.someValue > 1234; k++){
  myThing.action();
}

js2coffee.org indicates that I should use a while loop:

k = 1
while k < 120 and myThing.someValue > 1234
  myThing.action()
  k++

but this ends up compiling back to a while loop in javascript.

Is there a way to write coffescript to compile to my intended javascript and include extra conditions in the for loop itself?

If the answer to that question is false, then what would be the nicest way to get the same functionality with coffeescript?

My best while loop solution so far is

k = 1
myThing.action() while k++ < 120 and myThing.someValue > 1234
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Since a for loop is equivalent to a while loop plus a couple of statements, and CoffeeScript offers only one kind of for loop, use a while loop. If you’re trying to get specific JavaScript output, you should probably not be using CoffeeScript.

Of course, there is always

`for(k=1; k < 120 && myThing.someValue > 1234; k++) {`
do myThing.action
`}`

Avoid.


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

...