Why = cannot change the array, but push can?
This question already has an answer here:
So the reason this happens is because you are assigning the local variable the new array, whereas prior to the assignment, the local variable held the value of the passed in array.
The parameter holds a reference to the value passed in. However, the parameter is still a local variable. Writing to that variable will only modify the local variable, and will lose the reference held.
To expand, from being called:
init(array);//call function init with value array
Next the context environment is created upon instantiation, it holds a local variable array
, and the value of that variable is the same as the value of the passed in array
(in your example they have the same name)
function init(array) {
After this, two values are pushed to the value of array
, which is the value of the passed in array
.
array.push('1');
array.push('2');
Here is where it seemed the confusion took place. The local variable array
(still holding the value of the passed in array
) has its value changed to a new array. The result is that the local variable array
no longer holds the value of the passed in array
, but now holds the value of ['a','b']
.
array = ['a', 'b'];
That is why it looks like you cannot change the array by assignment - because the only thing you have access to in that scope is the local variable with regards to the original array.
function init(array) {
array.push('a');
array.push('b');
}
链接地址: http://www.djcxy.com/p/20986.html
上一篇: 修改函数参数并保持的函数
下一篇: 为什么=不能改变数组,但推可以?