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

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

    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
    

提交回复
热议问题