2014-02-23 64 views
2

我正在向數組中推入一些函數,但我不確定如何在循環數組時運行函數。運行存儲在數組中的函數

我想要得到redyellow​​輸出到控制檯。

這裏是一個小提琴我的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(); 

回答

3

myArr[i]是一個函數引用。你怎麼稱呼它指的是就像你做其他任何時候你有一個函數引用的功能,具有()

在你的循環,變化:

myArr[i]; 

myArr[i](); 
+0

謝謝!這可能看起來很愚蠢,但我並不太熟悉數組,這就是爲什麼我試圖將函數推入它們的原因。一個數組中的函數被記錄爲'[function,function,function]'是否正常?我試圖將它作爲函數的名稱進行記錄。再次感謝T.J! – Mdd

+1

@Mdd:樂於幫忙。你的函數沒有名字,你使用匿名函數表達式來創建它們:'function(){logIt(arg); }'。根據您使用的瀏覽器,如果他們確實有名字,則在轉儲到控制檯時可能會看到它們,也可能看不到它們。 –

+0

非常感謝您的解釋:) – Mdd

1

查看如何我正在執行myArri;下面是

你已經差不多了,你只是忘了()。

//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](); 
    }; 
}; 
+0

感謝您的快速回復! – Mdd

0

這是所有關於JavaScript的閉包是如何工作的,這通常是我們教的JavaScript閉包的方式,讓你的樣品是一個很好的,因爲它明確的概念。

這是我的方式通常會做同樣的事情,教JavaScript的關閉,這是完全與你相似的一些小分歧:

var myArr = []; 
myArr.push('red'); 
myArr.push('yellow'); 
myArr.push('green'); 

var funcArr=[]; 
function pushIt() { 
    for (var i = 0, len = myArr.length; i < len; i++) { 
     var func = (function(color){ 
      return (function(){ 
       console.log(color); 
      }); 
     })(myArr[i]); 
     funcArr.push(func); 
    }; 
}; 
function runIt() { 
    for (var i = 0, len = funcArr.length; i < len; i++) { 
     funcArr[i](); 
    }; 
}; 
pushIt(); 
runIt();