JavaScript数字排序代码说明
我正在经历下面的降序数字排序代码并感到困惑:JavaScript数字排序代码说明,javascript,arrays,sorting,Javascript,Arrays,Sorting,我正在经历下面的降序数字排序代码并感到困惑: var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a}); 上述代码将返回(b-a),例如100-40=60 但是阵列中没有60个。- 如果比较函数(a,b)小于0,则将a排序为低于b的索引,即a排在第一位 如果compareFunction(a,b)返回0,则保持a和b彼此不变,但根据所有不同的元素进行排序。注意:ECMAscript标准不保证这
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
上述代码将返回(b-a),例如100-40=60
但是阵列中没有60个。-
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){
console.log("a = " + a +
": b= " + b +
": b - a = " + (b - a) +
" swap a and b if b-a > 0");
return b - a});
输出-
a = 40: b= 100: b - a = 60 swap a and b if b-a > 0
a = 40: b= 1: b - a = -39 swap a and b if b-a > 0
a = 1: b= 5: b - a = 4 swap a and b if b-a > 0
a = 40: b= 5: b - a = -35 swap a and b if b-a > 0
a = 1: b= 25: b - a = 24 swap a and b if b-a > 0
a = 5: b= 25: b - a = 20 swap a and b if b-a > 0
a = 40: b= 25: b - a = -15 swap a and b if b-a > 0
a = 1: b= 10: b - a = 9 swap a and b if b-a > 0
a = 5: b= 10: b - a = 5 swap a and b if b-a > 0
a = 25: b= 10: b - a = -15 swap a and b if b-a > 0
请阅读
sort
方法的工作原理,以及回调函数返回的值在排序过程中的意义。@shashankpatil如果对您有帮助,您可以将答案标记为正确,这样其他人也可以从中受益。