Why does my function change the argument when it modifies an array?
This question already has an answer here:
Objects, including arrays are assigned by reference in ECMAScript. So, when you modify the array in the function you are modifying the same array as you passed into the function, not a new copy of the array.
A quick way to perform a shallow copy of an array is using slice(0)
(and in some modern engines you can leave out the 0
). See this answer about copying an array.
Also see this answer for some examples.
var foo = [1,2,3];
bar = function1(foo);
bar = function2(foo);
bar = function3(foo);
function function1(newFoo){
return [newFoo,'a',1];
} //foo after function1 = 1,2,3
function function2(newFoo){
var otherFoo = newFoo.slice(0);
otherFoo[0] = 'a';
return otherFoo;
} //foo after function2 = 1,2,3
function function3(newFoo){
var otherFoo = newFoo.slice(0);
otherFoo.push('4');
return otherFoo;
} //foo after function2 = 1,2,3
In function2 and function3, you're modifying the input variable (by changing its contents).
In function1, you're not modifying the input variable; you're merely assigning it to point to something else with =
.
Objects (including arrays) are passed by reference - if you don't want to modify the input, the safest thing to do is make a copy of the input at the beginning of the function (before potentially modifying it). For arrays, you can do this with the slice
function: var copy = input.slice(0)
上一篇: Javascript变量跟踪他们的副本?
下一篇: 为什么我的函数在修改数组时修改参数?