我试图在每次运行此函数时创建一个单独的数组,目前它似乎每次运行时都会写入该函数。
我将如何做到这一点?任何帮助表示感谢,谢谢。
<script>
var a = [[4,1,2],[3,7,9],[2,3,5]];
function swap(x,y,m,n){
var src=x;
var dest = y;
var tmp = a[x][y];
a[x][y] = a[m][n];
a[m][n] = tmp;
newArray = new Array(a);
return newArray;
}
var tmp1 = new Array(swap(1,0,0,0));
var tmp2 = new Array(swap(1,0,2,0));
document.write(tmp1 + "<br>" + tmp2 + " <br>" + a);
</script>
答案 0 :(得分:0)
声明变量&#34; b&#34;在函数内部,它作为数组&#34; a&#34;的临时副本,阻止在函数期间更改它。
<script>
var a = [[4,1,2],[3,7,9],[2,3,5]];
function swap(x,y,m,n){
var b = a;
var src=x;
var dest = y;
var tmp = b[x][y];
b[x][y] = b[m][n];
b[m][n] = tmp;
newArray = new Array(b);
return newArray;
}
var tmp1 = new Array(swap(1,0,0,0));
var tmp2 = new Array(swap(1,0,2,0));
document.write(tmp1 + "<br>" + tmp2 + " <br>" + a);
</script>