Pinguto Pinguto - 10 days ago 6
Javascript Question

Output abnormal .. WHY?

I have many days that I can not run this script!



var b = [9,8,7,6,5,4,3,2,1];
var a = (function(){
var W = [];
for(var k in b){
W[W.length] = {
index : k,
fx : function(){
console.log(k);
}
}
}
return W;
})();

console.log(a);
for(var j = 0; a[j]; j++)a[j].fx();





Because it does not produce as OUTPUT numerical sequence 987654321?

qxz qxz
Answer

Each function fx that you create references the variable var k. They don't save the current value of k, only a reference to k. This means that when you run the functions, after the for loop has finished, the value of k is now 8, and they all print that.

Once way to avoid this, and give each function its own variable/value, is to change var k to let k (available since ECMAScript 6). See let at MDN.

var b = [9,8,7,6,5,4,3,2,1]; 
var a = (function(){ 
  var W = []; 
  for (let k in b) { 
    W[W.length] = { 
      index : k, 
      fx : function(){ 
        console.log(k); 
      } 
    } 
  } 
  return W; 
})(); 
 
for(var j = 0; a[j]; j++)
  a[j].fx();

Comments