[英]How to take break out of for loop
我想從 for 循環中取出 if 條件來解決圈復雜度。 如何從 for 循環中取出 break 語句?
這是示例代碼。 abc2
是原始函數
function abc2() { for(var i=1; i<8; i++){ if (i == 5) break console.log(i) } } function abc() { for(var i=1; i<8; i++) { aa(i) console.log(i) } } function aa(i) { if (i == 5) break // how to use break here }
<html> <body> <button type = "button" onclick = "abc()">Click.</button> </body> </html>
您可以重構aa(i)
函數以返回boolean
。 break 語句從開關或循環中中斷,這與您在上面顯示的情況不同,因此您收到錯誤。
function abc(){ for(var i=1; i<8; i++){ if (aa(i)){ console.log(i) break; } } } function aa(i){ return i == 5; } abc();
從更抽象的角度來看,您打算編寫一個函數來影響調用上下文中的程序流。
除了從函數返回一個值或設置一些可從上下文訪問的狀態(即產生副作用)之外,這是行不通的——這是正確的,因為它違反了軟件工程的基本最佳實踐(即封裝和局部性)並保證需要難以推理和維護的代碼。 請注意,許多經驗豐富的開發人員已經對副作用感到不滿。
你可以做的是改變循環界限;
將循環分成兩個或修改增量操作:
function abc(){
for(var i=1; i<5; i++){
aa(i);
console.log(i)
}
// Now handle special case i == 5. Higher values of i will not be reached with the original loop definition
}
也許您打算在原始循環中跳過i==5
。 您應該將循環拆分為 2:
function abc(){
for(var i=1; i<5; i++){
aa(i);
console.log(i)
}
for(var i=6; i<8; i++){
aa(i);
console.log(i)
}
}
如果您經常應用這些模式,您可能希望將其推廣到某些功能中。
或者,修改增量:
function abc(){
for(var i=1; i<8; i = (i === 4) ? (i+2) : (i+1)){
aa(i);
console.log(i)
}
}
我不確定是否可以取出 if 因為它是一個條件,並且您需要使用 if 或其他一些條件來排除該條件。 也許就像做/一會兒。
如果你只想跳過 5 的值,你可以使用這個:
function abc2(){
for(var i=1; i<8;) {
if(i==5){
// don't run any code here, just increment i
i++;
} else {
someFunction() // run whatever code you want
i++; // then increment i
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.