-4

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?

Pinguto
  • 416
  • 3
  • 17

1 Answers1

3

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();
qxz
  • 3,814
  • 1
  • 14
  • 29
  • Uh .. Thanks! I noticed that **LET** is only supported by the latest browsers. how can I do to increase compatibility with **older browsers**? – Pinguto Nov 26 '16 at 07:12
  • See [the accepted answer on the duplicate](http://stackoverflow.com/a/750506/1848578) for several solutions. – qxz Nov 26 '16 at 07:14