關(guān)于排序函數(shù)的返回值
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Array對(duì)象 </title>
<script type="text/javascript">
? ?function sortNum(a,b) {
? ? ? ?if(a>=b){
? ? ? ? ? ?return 1
? ? ? ?}
? ? ? ?else{
? ? ? ? ? ?return -1
? ? ? ?}
? ?}
var myarr = new Array("80","16","50","6","100","1");
document.write(myarr.sort(sortNum));
</script>
</head>
<body>
</body>
</html>
為什么我寫(xiě)的排序函數(shù),最終沒(méi)有按順序排呢,是亂序
輸出結(jié)果為:1,100,16,50,6,80
2018-04-25
因?yàn)閿?shù)組里存的字符串呀,(重點(diǎn))字符串比較大小和數(shù)字比較大小是不一樣的,可以這樣寫(xiě):if(parseInt(a)>=parseInt(b)){return 1}else{return -1} 先把字符串轉(zhuǎn)成數(shù)字再比較大小