我正在向數組中推入一些函數,但我不確定如何在循環數組時運行函數。運行存儲在數組中的函數
我想要得到red
yellow
輸出到控制檯。
這裏是一個小提琴我的JavaScript:http://jsfiddle.net/rYNv4/
這裏是我迄今爲止以及代碼:
var myArr = [];
myArr.push(logItRunner('red') );
myArr.push(logItRunner('yellow'));
myArr.push(logItRunner('green') );
console.log(myArr);
//Function to be stored in array. Should return the logIt function.
function logItRunner(arg) {
return function() {
logIt(arg);
};
}
//Function to log a string to the console
function logIt (color) {
console.log(color);
};
//Function to loop through array and fire functions within the array
function runIt() {
for (var i = 0, len = myArr.length; i < len; i++) {
//Fire Function within Array at position i and log the argument to the console.
myArr[i];
};
};
runIt();
謝謝!這可能看起來很愚蠢,但我並不太熟悉數組,這就是爲什麼我試圖將函數推入它們的原因。一個數組中的函數被記錄爲'[function,function,function]'是否正常?我試圖將它作爲函數的名稱進行記錄。再次感謝T.J! – Mdd
@Mdd:樂於幫忙。你的函數沒有名字,你使用匿名函數表達式來創建它們:'function(){logIt(arg); }'。根據您使用的瀏覽器,如果他們確實有名字,則在轉儲到控制檯時可能會看到它們,也可能看不到它們。 –
非常感謝您的解釋:) – Mdd