我在这里读到了很多关于"按值"和"按引用"传递以将数组发送到javascript函数的答案.然而,我在向函数发送数组并使原始数组保持不变时遇到问题.这个例子说明了这个问题:
function myFunction(someArray)
{
// any function that makes an array based on a passed array;
// someArray has two dimensions;
// I've tried copying the passed array to a new array like this (I've also used 'someArray' directly in the code);
funcArray = new Array();
funcArray = someArray;
var i = 0;
for(i=0; i<funcArray.length; i++)
{
funcArray[i].reverse;
}
return funcArray;
}
Run Code Online (Sandbox Code Playgroud)
我无法理解为什么这个函数中的任何东西都应该改变原始数组.
如果将函数调用分配给新数组,则调用此函数会直接更改原始数组:
myArray = [["A","B","C"],["D","E","F"],["G","H","I"]];
anotherArray = new Array();
anotherArray = myFunction(myArray);
// myArray gets modified!;
Run Code Online (Sandbox Code Playgroud)
我尝试使用.valueOf()发送原语:
anotherArray …Run Code Online (Sandbox Code Playgroud)