2011-05-04 15 views
2

的我一直相信您使用繼續如下:正確使用繼續在javascript

var i; 

for (i = 0; i < 10; i++) { 
    if(i%2===0) { 
    continue; 
    } 
} 

或者

var i, myloop; 

myloop: for (i = 0; i < 10; i++) { 
    if(i%2===0) { 
    continue myloop; 
    } 
} 

但是當我通過JSLint運行的代碼,這兩個片段,我明白錯誤:

 

Problem at line 5 character 5: Unexpected 'continue'. 
    continue; 

我在做什麼錯?什麼是正確的用法?

+1

你必須將'var i'移動到甚至更遠的地方,對吧?改善你的代碼是JSLint的第二個擔憂,強調Doug Crockford關於JavaScript的個人觀點是第一個。如果你想要一個不那麼固執的選擇,總會有[JSHint](http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/)。 – 2011-05-04 15:48:59

+1

是的。 JSHint。 JSLint太教條了。 – 2012-09-29 09:18:33

回答

2

我猜JSLint just hates continue

There are almost always better ways of writing statements that more explicitly define what you are attempting to do without resorting to continue. JSLint is all about the good parts, and not about the parts that are acceptable. It forces you to use a higher standard than the one defined.

Douglas says it best in his book:

"The continue statement jumps to the top of the loop. I have never seen a piece of code that was not improved by refactoring it to remove the continue statement."

+1

雖然這很愚蠢。 '繼續'可以很容易地在一個循環中'提前退出'。我猜內部循環可以放在外部函數中,以保持可讀性,但這並不總是方便。 – Evert 2011-05-04 15:38:05

+0

@Evert:你一定會感到困惑,繼續休息(這是你說的話,而不是克羅克福德所不喜歡的)。 – xofon 2011-05-04 16:35:37

+1

不,對不起..說你想循環一個數組,但只做某些元素在該數組中。如果(!condition)繼續,我可以這樣做;在循環的頂部,或者如果(條件){..}東西。前者的優點是嵌套層次較少。 – Evert 2011-05-05 07:48:39

3

您必須勾選 「容忍繼續」,克羅克福德不like it

0

有一個在JSLint的底部,上面寫着

容忍的選項繼續

也許它有問題呢?

0

JSLint不喜歡continue,因爲道格拉斯不喜歡它。

continue跳到下一次迭代。如果你不插入它,代碼將繼續執行。如果您想退出循環,請使用break