我有一個循環數組的函數...雖然它的工作似乎改變了從「開始」函數發送到「處理」函數的信息的值,但我不知道「知道爲什麼......我敢肯定,我犯了一個愚蠢的錯誤,但我看不到錯誤=/JS數組傳遞值無理變化
這是我的函數:
var array_data = data[9]; //global array to use
console.log(array_data); //debug
function process(i){
alert('Number is '+i); // shows the value "7" (should show value "1")
}
function begin(){
var count = 0;
for(i in array_data){
if(parseInt(array_data[i][9])){ //if true
var result = create_layout(i); //function to make the layout
alert('Number is '+i); //shows the value "1" (this is correct so far)
document.getElementById('result'+count).innerHTML = result;
document.getElementById('result'+count).onclick = function() { process(i); };
count++;
}
}
window.onload = function() {
begin();
};
下面是我對陣列(array_data)從控制檯日誌:
1: Array[10]
0: "Car One"
1: "1"
2: "3"
3: "d2.jpg"
4: "1"
5: "1"
6: "200"
7: "85"
8: "5000"
9: "1"
length: 10
7: Array[10]
0: "Car Two"
1: "1"
2: "1"
3: "e2.jpg"
4: "1"
5: "0"
6: "500"
7: "50"
8: "3000"
9: "0"
length: 10
所以我想知道爲什麼當它達到過程函數時它會改變「我」的價值?
爲什麼它會改變這個div,雖然肯定有一次它的循環並將它分配給div ID result0下一個循環會將它分配給div ID result1? – Sir 2012-07-25 23:21:01
是的,但'i'的實際值發生了變化。函數不是常量,它們是閉包,它們繼承了它們包含的範圍的變量。如果這些變量在該範圍內發生變化,該函數將反映該變化。 – 2012-07-25 23:22:25
因此,將div id =「result0」設置爲值爲「1」的i在瀏覽器中並不是一成不變的,而是變量i。 – Sir 2012-07-25 23:25:14