问题
Why does the first function not modify the original array like the second function does?
var a= [3, 4, 5];
function doesNothing(a) {
a=[1,1,1];
}
function doesSomething(a) {
a.push(6);
}
doesNothing(a);
console.log(a); // [3,4,5] not [1,1,1]
doesSomething(a);
console.log(a); //[3,4,5,6]
回答1:
The first function makes no attempt to modify the array. All it does is assign a new value to the parameter that, when it was called, was given a copy of a reference to the array. The variable a in the first function is just a variable with an object reference as its value. The assignment statement just changes its value, exactly as if your function had
a = 5;
instead.
Note that you've declared the first function with a as a parameter - that symbol a hides the a outside the function.
The second function does modify the array because it calls a method on the array object that modifies it.
回答2:
Try this
var a= [3, 4, 5];
function doesNothing() {
a=[1,1,1];
}
function doesSomething() {
a.push(6);
}
doesNothing(a);
console.log(a);
doesSomething(a);
console.log(a);
回答3:
Because in your first function, the statement a = initializes a new variable in local scope (it essentially translates to var a =) completely unrelated to the global a variable, whereas in the second function, you're calling upon and mutating the original array passed into it.
来源:https://stackoverflow.com/questions/29980563/javascript-can-modify-array-passed-to-function-only-sometimes