I cant get a hang on closures. A very simple example:
var array = [1,2,3];
var test = [0,0];
var result = [];
for (var i=1; i<=array.length; i++){
test[1] = i;
result.push(test);
}
console.log(result);
If I just push "i" into the result, it outputs "1,2,3", but the way above I always get "[0,3],[0,3][0,3]". Why is that? I have read some explanations on closures, but I dont seem to understand the system, which makes it very hard to find additional errors in my code. Isnt there an easier way to resolve the problem above, than using functions inside functions (that seems to be the solution to every equivalent problem I have found so far)?
You are writing same instance to result and when you change parameter in that instance, all instances in result are changed. You need to create separate instances to keep data, here is code to illustrate right way to do this
var array = [1,2,3];
var test = [0,0];
var result = [];
for (var i=1; i<=array.length; i++){
var z = [test[0], i];
result.push(z);
}
console.log(result);
The point is when you substitute Array in JavaScript, It's not copying but giving a link to the Array. So
var testArray = [1,2,3];
var copy = testArray;
copy[1] = 10;
console.log(testArray); // [1,10,3]
to avoid this, you can "copy" Array by .concat() or .slice()
var testArray = [1,2,3];
var copy = testArray.concat(); // or Array.slice(0)
copy[1] = 10;
console.log(testArray) // [1,2,3]
so your code would be
var array = [1,2,3];
var test = [0,0];
var result = [];
for (var i=1; i<=array.length; i++){
test[1] = i;
result.push(test.concat());
}
console.log(result);