js基础问题:大家看看为什么上一个数组会影响到下一个数组。
以下是正确的js代码:function sortNumber(a,b)
{
return a - b;
}
function test()
{
var arr1 = new Array();
arr1[0] = "1";
arr1[1] = "100";
arr1[2] = "2";
arr1[3] = "300";
arr1[4] = "6";
arr1[5] = "1000";
var arr2 = arr1.sort();
document.write(arr2 + "<br />");
document.write(arr2.join("-") + "<br /><br />");
var arr3 = arr1.sort(sortNumber);
document.write(arr3 + "<br />");
document.write(arr3.join("-"));
}
{
return a - b;
}
function test()
{
var arr1 = new Array();
arr1[0] = "1";
arr1[1] = "100";
arr1[2] = "2";
arr1[3] = "300";
arr1[4] = "6";
arr1[5] = "1000";
var arr2 = arr1.sort();
document.write(arr2 + "<br />");
document.write(arr2.join("-") + "<br /><br />");
var arr3 = arr1.sort(sortNumber);
document.write(arr3 + "<br />");
document.write(arr3.join("-"));
}
输出为:
1,100,1000,2,300,6
1-100-1000-2-300-6
1,2,6,100,300,1000
1-2-6-100-300-1000
1-100-1000-2-300-6
1,2,6,100,300,1000
1-2-6-100-300-1000
下面是错误的:
function sortNumber(a,b)
{
return a - b;
}
function test()
{
var arr1 = new Array();
arr1[0] = "1";
arr1[1] = "100";
arr1[2] = "2";
arr1[3] = "300";
arr1[4] = "6";
arr1[5] = "1000";
var arr2 = arr1.sort();
var arr3 = arr1.sort(sortNumber);
document.write(arr2 + "<br />");
document.write(arr2.join("-") + "<br /><br />");
document.write(arr3 + "<br />");
document.write(arr3.join("-"));
}
{
return a - b;
}
function test()
{
var arr1 = new Array();
arr1[0] = "1";
arr1[1] = "100";
arr1[2] = "2";
arr1[3] = "300";
arr1[4] = "6";
arr1[5] = "1000";
var arr2 = arr1.sort();
var arr3 = arr1.sort(sortNumber);
document.write(arr2 + "<br />");
document.write(arr2.join("-") + "<br /><br />");
document.write(arr3 + "<br />");
document.write(arr3.join("-"));
}
输出为:
1,2,6,100,300,1000
1-2-6-100-300-1000
1,2,6,100,300,1000
1-2-6-100-300-1000
1-2-6-100-300-1000
1,2,6,100,300,1000
1-2-6-100-300-1000
问题是:为什么错误的代码中,arr2会影响到arr3