JS数组无理由地传递值更改

JS Array passing value changes for no reason

本文关键字:数组 无理由 JS      更新时间:2024-02-15

我有一个函数,它循环数组。。。当它工作时,它似乎将发送的信息的值从"开始"函数更改为"处理"函数,但我不知道为什么。。。我确信我犯了一个愚蠢的错误,但我看不出这个错误

这是我的功能:

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

所以我想知道,当它到达过程函数时,为什么会改变"I"的值?

onclick函数被实际调用时,i的值将因为它所在的循环而发生变化。您应该"锚定"它的值。最简单的方法是这样的:

for( some loop on `i`) {
    (function(i) {
        // your code that depends on `i`
    })(i);
}

这将确保i的值不会在该闭包内更改(除非您自己更改)

  • 不要在数组上使用for in循环(好,此处不适用)
  • begin函数缺少右大括号
  • 只需使用window.onload = begin;-不需要额外的功能
  • 然而,您的i变量需要一个额外的闭包。执行事件处理程序时,它将使用变量i,其当前值是它在上一个循环周期中得到的值。count变量可能也有同样的问题
for(var i=0; i<array_data.length; i++) (function(i){
    <...>.onclick = function() { ...i...; };    
})(i);

在ECMAScript 5中,您可以继续使用bind将参数绑定到您的函数:

document.getElementById('result' + count).onclick = process.bind(null, i);

如果你不必担心Internet Explorer 8和早期版本,这将是一个很好的选择。