Javascript开发中,数组是用到最多一个内容。同时数组的方法不多,下面介绍在数组排序中用到的2个常用方法。sort()方法和reverve()方法。
sort()方法可以很容易将一个数组进行排序,可以根据字母的ASC码大小和数字大小来排序。
reverse()方法可以理解反序操作。
下面通过数组的sort()方法和reverse()方法来完成一个小的需求。
<script type="text/javascript">
//
/*
需求:
Num1,Num2,Num3,Num4,在程序运行中,这四个数会发生改变,找出最大的那个数字对应的变量。假设
Num1=10,Num2=3,Num3=80,Num4=34;
输出的结果应该是:NumD
*/
var Num1=40, Num2=20, Num3=90, Num4=5;
arrayLength=4;
var numArray=new Array();
for (var i = 0; i < arrayLength; i++) {
numArray.push(Num1);
numArray.push(Num2);
numArray.push(Num3);
numArray.push(Num4);
}
//复制数组
var tempArray=new Array();
for (var i = 0; i < 4; i++) {
tempArray[i]=numArray[i];
}
var sortedNum = tempArray.sort().reverse();
var maxNum = sortedNum[0];
var myindex;
for (var j = 0; j < arrayLength; j++) {
if (numArray[j] == maxNum) {
myindex = parseInt(j)+1;
break;
}
}
document.write("The max number in the Array:Num" + myindex + "<br/>");
</script>
在Javascript中进行数组复制,使用for循环的方法,性能消耗很大。可以使用slice()或contact()方法。
<!-- .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } -->