3-8的第一位同學(xué)的代碼,看不懂?
? ? //按照字符數(shù)排序
? ? arr.sort(function(a, b){
? ? ? ? if(a.length > b.length){
? ? ? ? ? ? return 1
? ? ? ? }else if(a.length < b.length){
? ? ? ? ? ? return -1
? ? ? ? }else{
? ? ? ? ? ? return 0
? ? ? ? }
? ? })
? ??
這段排序代碼怎么解釋啊,為什么sort()里面寫function
2016-08-02
他把函數(shù)直接定義在sort()所需參數(shù)中了,因?yàn)閟ort泵就需要一個(gè)參數(shù)來確定如何排序的
相當(dāng)于:
? //按照字符數(shù)排序
function s(a,b){
?if(a.length > b.length){
? ? ? ? ? ? return 1
? ? ? ? }else if(a.length < b.length){
? ? ? ? ? ? return -1
? ? ? ? }else{
? ? ? ? ? ? return 0
? ? ? ? }
}
? ? arr.sort(s(a, b));
2016-08-02
<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>
給sort加函數(shù)規(guī)定它的排序。。大概就是這樣,第一次回答,不知道能不能幫到你
2016-08-02
sort()里面寫function是因?yàn)閟ort方法中有一個(gè)排序規(guī)則,規(guī)定了排序的方式。不加這個(gè)函數(shù),默認(rèn)的sort()方法會(huì)按unicode碼順序排列。這里的function規(guī)定了按字符的長(zhǎng)度進(jìn)行排序的規(guī)則。
2016-08-02
function定義函數(shù)的關(guān)鍵字