Discuss
/
JavaScript
/
这样写不是更简洁
这样写不是更简洁
Topic sourcevar arr = [10, 20, 1, 2]; arr.sort(function (x, y) { if (x < y) { return -1; } if (x > y) { return 1; } return 0; }); // [1, 2, 10, 20]
小白求指点,内部function函数返回的1和-1返到哪里去了?这个函数究竟是如何运作的?
注意听讲啊这位同学,如果x大于y则返回1,x小于y则返回-1,顺便给大家提供一个随机排序的方法:
Id_arr.sort(function () {
return 0.5-Math.random()
})
这样就能把数组里的东西打乱排序啦!
- 1
hanashin
arr.sort(function (a, b){ return a - b; }); //正序排列数字
arr.sort(function (a, b){ return b - a; }); //倒序排列数字