<script type="text/javascript"> var myarr1 = new Array("Hello","John","love","JavaScript"); var myarr2 = new Array("80","16","50","6","100","1"); document.write(myarr1.sort()+"<br>"); document.write(myarr2.sort()); </script>
运行结果:
Hello,JavaScript,John,love 1,100,16,50,6,80
注意:上面的代码没有按照数值的大小对数字进行排序。
2.如要实现这一点,就必须使用一个排序函数,代码如下:
<script type="text/javascript"> function sortNum(a,b) { return a - b; //升序,如降序,把“a - b”该成“b - a” } var myarr = new Array("80","16","50","6","100","1"); document.write(myarr + "<br>"); document.write(myarr.sort(sortNum)); </script>
运行结果:
80,16,50,6,100,1 1,6,16,50,80,100
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,同时也希望多多支持脚本之家!
您可能感兴趣的文章: