示例 7 :
分别在最开始的位置插入数据和获取数据(获取后删除)
方法 unshift shift ,分别在最开始的位置插入数据和获取数据(获取后删除)
<script> function p(s){ document.write(s); document.write("<br>"); } var x = new Array(3,1,4); p('数组x是:'+x); x.unshift (5); p('对数组 unshift 值5(在最前面加),数组变为:' + x); var e = x.shift (); p('从数组中 shift 一个数(从最前面取),其值是:' + e); p('shift之后,数组变为:' + x); </script>
示例 8 :
对数组的内容进行排序
方法 sort对数组的内容进行排序
<script> function p(s){ document.write(s); document.write("<br>"); } var x = new Array(3,1,4,1,5,9,2,6); p('数组x是:'+x); x.sort(); p('使用sort排序后的数组x是:'+x); </script>
示例 9 :
自定义排序算法
sort()默认采用正排序,即小的数排在前面。 如果需要采用自定义排序的算法,就把比较器函数作为参数传递给sort()。
比较器函数:
function comparator(v1,v2){
return v2-v1; //v2-v1表示大的放前面,小的放后面
}
调用sort函数的时候,把这个比较器函数comparator作为参数传递进去即可
x.sort(comparator);
<script> function p(s){ document.write(s); document.write("<br>"); } function comparator(v1,v2){ return v2-v1; } var x = new Array(3,1,4,1,5,9,2,6); p('数组x是:'+x); x.sort(comparator); p('使用sort 进行自定义倒排序后的数组x是:'+x); </script>