Hongbo Miao Hongbo Miao -5 years ago 98
Javascript Question

Why = cannot change the array, but push can?

I want to use

to initiate an array in a function. However,
cannot change the array, but

I want it equals to
["a", "b"]
. But now the result is
["1", "2"]

I tried
arr = ['a', 'b'];
and also
arr = ['a', 'b'].slice();
. But neither works.

How can I let
work in this case?

var array = [];


function init(arr) {
arr = ['a', 'b'];


Answer Source

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download