哪位大神教教我这段JavaScript代码s.sort(function(a,b){return a-b;});中的function怎么理解,其中s是数
改了下,可以看到排序过程,看看就知道了
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟</title>
</head>
<body>
<p id="demo">单击按钮降序排列数组。</p>
<p id="debug">测试效果</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
var points = [40,100,1,5,25,10];
points.sort(function(a,b){document.getElementById("debug").innerHTML +="a为"+a+"b为"+b+"结果为"+(b-a)+(function(){if (b-a<0){return "不动"} else {return "调换"}}()) +"<br>";return b-a});
var x=document.getElementById("demo");
x.innerHTML=points;
}
</script>
</body>
</html>
888, 2222, 9, 4 ·······return 9-888=-879 为负数(为什么和888比较而不和2222比较,因为这是一种折半比较,前面的位数是偶数/2,若前面是奇数/2 +1,此时是偶数,所以和第一位进行比较),9直接挪到888的前面(因为888和2222的关系已经明确,比888小就直接挪到888前面了)
9, 888, 2222, 4 ·······return 4-888=-884为负数,将4挪到888前面
9, 4, 888, 2222········return 4-9=-5为负数,将4挪到9前面
4, 9, 888, 2222·······完成 ,以上数据亲测有效
以上注释为我的推测,有错请指正,不用走流程 ( ̄3 ̄)a
2018-05-21
The Compare Function
The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the arguments:
function(a, b){return a-b}
When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
Example:
When comparing 40 and 100, the sort() method calls the compare function(40,100).
The function calculates 40-100, and returns -60 (a negative value).
The sort function will sort 40 as a value lower than 100.
You can use this code snippet to experiment with numerically and alphabetically sorting:
<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>
<p id="demo"></p>
<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
广告 您可能关注的内容 |