I do not know how js engine handle the difference between two scripts below:
var a = [];
for (i = 0 ; i< 10 ; i++ ){
var temp = {};
var k = i;
temp.test = function (){
return k;
}
a.push(temp);
}
for (i = 0 ; i<10 ;i++ ){
console.log(a[i].test());
}
Output
999999999
var a = [];
for (i = 0 ; i< 10 ; i++ ){
var temp = {};
temp.test = function (){
var k = i; //<--------------------- this line is moved
return k;
}
a.push(temp);
}
for (i = 0 ; i<10 ;i++ ){
console.log(a[i].test());
}
output 123456789
The output is from running the script in node.js
Sometime even bizarre: If the script is run in chrome, the output is both: 999999999
I think chrome and node.js all use V8 engine, why different?