Please look at these 3 code blocks first.
Code Block 1:
var t1 = function(aaa) {
setTimeout(function(){
a = 'bb';
aaa.push(a);
}, 1000);
}
var t3 = function() {
var aa = new Array;
aa[0] = 'aa';
console.log(aa);
t1(aa);
setTimeout(function(){
console.log(aa);
}, 3000);
}
t3();
Output:
[ ‘aa’ ]
[ ‘aa’, ‘bb’ ]
Code Block 2:
var t1 = function(aaa) {
setTimeout(function(){
aaa[1] = 'bb';
}, 1000);
}
var t3 = function() {
var aa = new Array;
aa[0] = 'aa';
console.log(aa);
t1(aa);
setTimeout(function(){
console.log(aa);
}, 3000);
}
t3();
Output:
[ ‘aa’ ]
[ ‘aa’, ‘bb’ ]
Code Block 3:
var t1 = function(aaa) {
setTimeout(function(){
aaa = aaa.concat('bb');
}, 1000);
}
var t3 = function() {
var aa = new Array;
aa[0] = 'aa';
console.log(aa);
t1(aa);
setTimeout(function(){
console.log(aa);
}, 3000);
}
t3();
Output:
[ ‘aa’ ]
[ ‘aa’ ]
The problem is code block 3 that the ‘concat’ method can’t modify the ‘aaa’ var pass by argument.
What’s the difference of ‘concat’ ,’push’ and direct modify?
In codeblock 1 and 2, you are modifying the contents of
aa.While in codeblock 3 you are rebinding
aaato another array, and theaaain functiont1is not a reference to the outsideaaanymore. So the outsideaais not being modified.you can refer to Is JavaScript a pass-by-reference or pass-by-value language? to see the detailed explanation on Javascript’s variable passing behavior.