Mutate JavaScript Array Inside Function

前端 未结 1 1823
一生所求
一生所求 2021-01-20 15:45

In JavaScript, how do I mutate the value of an array inside of a function? I know that happens when using certain array methods, but it doesn\'t seem to work for normal assi

1条回答
  •  -上瘾入骨i
    2021-01-20 16:33

    You can use .splice:

    arr.splice(0, arr.length, 1, 2, 3);
    

    Or you can empty the array and .push the values:

    arr.length = 0;
    arr.push(1, 2, 3);
    // or given an array of values
    arr.push.apply(arr, newValues);
    

    However, make sure it is clear that the function changes the array in place. While there are native functions that does this (like Array#sort), I'd argue that this is not as common as simply returning a new array.


    It's my understanding that this code doesn't change the value of "arr" outside of the function.

    Correct. Assigning a new value to a variable or property never changes the value of another variable or property (exceptions: global scope and with statements). You basically tried to change the value of a variable, not mutate the value itself.

    JavaScript is call/pass/assign by value (Wikipedia also mentions "by sharing"), not by reference.

    0 讨论(0)
提交回复
热议问题