2014-09-02 42 views
0

我想知道這個foreach循環是如何工作的(請參閱復位功能)。 我猜我可以調用somePropertyManagerArray.reset();並且它會對它執行一個foreach循環。我並沒有把握循環中發生的事情。不清楚這個JavaScript代碼如何工作。

PropertiesManager = function() { 
    this.controls = {}; 
    this.controlNames = []; 
}; 
PropertiesManager.prototype = { 
    // code block removed // 
    reset: function(selectedControls) { 
     var controls = this.controls; 
     **Array.forEach(selectedControls || this.controlNames, function(control) { 
      controls[control].reset(); 
     });** 
    } 
}; 
+3

如果它存在,它將通過'selected controls'循環,否則循環'this.controlNames'。然後,對於每個控件,它會在'controls'字典中獲取相應的條目並調用其自己的重置功能。 – Renan 2014-09-02 20:12:38

回答

1

讓我重新寫一個函數在一個更詳細的方式:

reset: function(selectedControls) { 
    var controls = this.controls; 

    var arrayToIterate; 
    if (selectedControls) { 
     arrayToIterate = selectedControls; 
    } else { 
     arrayToIterate = this.controlNames; 
    } 

    Array.forEach(arrayToIterate, function(control) { 
     controls[control].reset(); 
    }); 
} 

||運算符是or操作。如果第一個值是虛假的,那麼它將使用第二個值。 undefinednull和其他值的少數資格作爲falsey,這是false.

1

selectedControls || this.controlNames的意思是 「selectedControls循環,但如果是null或undefined遍歷this.controlNames」。

Array.forEach()的第二個參數是爲數組中的每個條目運行的函數,其參數是數組中的當前項(控制)。

1

在foreach功能用於一次在一個陣列中的每個值執行一個或多個功能的寬鬆得多的定義。 例如:

function logResult(element) { 
console.log(element); 
} 
//and then performing this operation: 
["Apples", "Oranges", "Bananas"].forEach(logResult); 
//Would log "Apples", then "Oranges", and then "Bananas" to the console. 

你的例子裏面的處理是檢查selectedControls是否被定義。如果是,請循環播放。如果不是,則循環this.controlNames

參考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

1
var a = ["a", "b", "c"]; 
a.forEach(function(entry) { 
    console.log(entry); 
}); 

這裏的forEach採取在一個時間的陣列中的每個元素(在每一個循環)從索引0和打印的「a」在第一環路中,「b」,在第二循環開始和第三循環中的「c」。

輸出在控制檯:A B C

在代碼

Array.forEach(selectedControls || this.controlNames, function(control) { 
     controls[control].reset(); 
    }); 

它採取selectedControls數組或對象或controlNames陣列或對象(如果selectedControls爲空),並通過此循環。 control是數組的元素,它在每次循環中一次迭代。