Discuss / JavaScript / 这样写不是更简洁

这样写不是更简洁

Topic source

hanashin

#1 Created at ... [Delete] [Delete and Lock User]

arr.sort(function (a, b){ return a - b; }); //正序排列数字

arr.sort(function (a, b){ return b - a; }); //倒序排列数字

桔小涵

#2 Created at ... [Delete] [Delete and Lock User]

所以老师很体谅我们这些编程小白啊

郭秋志

#3 Created at ... [Delete] [Delete and Lock User]

var 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返到哪里去了?这个函数究竟是如何运作的?

-1,0 ,1 应该是一开始提到的排序规则吧!

注意听讲啊这位同学,如果x大于y则返回1,x小于y则返回-1,顺便给大家提供一个随机排序的方法:


Id_arr.sort(function () {
        return 0.5-Math.random()
    })

这样就能把数组里的东西打乱排序啦!


  • 1

Reply