Javascript passing arrays to functions by value, leaving original array unaltered

前端 未结 9 1816
不思量自难忘°
不思量自难忘° 2020-11-28 11:01

I\'ve read many answers here relating to \'by value\' and \'by reference\' passing for sending arrays to javascript functions. I am however having a problem sending an array

9条回答
  •  醉梦人生
    2020-11-28 11:51

    With ES6, you can use the spread syntax and destructuring to perform a shallow copy directly in the argument list, allowing you to keep the original array unaltered.

    See example below:

    const arr = [1, 2, 3, 4, 5];
    
    function timesTen([...arr]) { // [...arr] shallow copy the array
      for(let i = 0; i < arr.length; i++) {
        arr[i] *= 10; // this would usually change the reference
      }
      return arr;
    }
    
    console.log(timesTen(arr));
    console.log(arr); // unaltered

提交回复
热议问题