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

前端 未结 9 1713
不思量自难忘°
不思量自难忘° 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

    If you need to do this with an object, try this fancy trick...

    MY_NEW_OBJECT = JSON.parse(JSON.stringify(MY_OBJECT));
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-28 11:51
    var aArray = [0.0, 1.0, 2.0];
    var aArrayCopy = aArray.concat();
    aArrayCopy[0] = "A changed value.";
    console.log("aArray: "+aArray[0]+", "+aArray[1]+", "+aArray[2]);
    console.log("aArrayCopy: "+aArrayCopy[0]+", "+aArrayCopy[1]+", "+aArrayCopy[2]);
    

    This answer has been edited. Initially I put forth that the new operator handled the solution, but soon afterward recognized that error. Instead, I opted to use the concat() method to create a copy. The original answer did not show the entire array, so the error was inadvertently concealed. The new output shown below will prove that this answer works as expected.

    aArray: 0, 1, 2
    aArrayCopy: A changed value., 1, 2
    
    0 讨论(0)
提交回复
热议问题