js 有自带排序方法 sort(), 默认 升序 排列
如:
data() { return { arr: [1,3,2,5,6,8,7,4,9] } },
控制台如下:
貌似没毛病,老铁~~~ 0.0
我们改变数组:
data() { return { arr: [1,3,2,5,11,10,20,50,6,8,7,4,9] } }
控制台如下:
what are you 弄啥咧? 什么鬼!!!
查了一波资料,因为 sort() 方法排序是根据 Unicode码 比较,所以无法完成这种数组的排序!怎么办咧?
看了几篇博客发现一个有效且到目前为止感觉最简单的一种方法:自定义比较
如下:
cmp: function(a, b) { return a - b }
原理:
参数 a ,b
如果 a > b 则 a - b > 0 返回一个正数
如果 a < b 则 a - b < 0 返回一个负数
如果 a = b 则 a - b = 0 返回 0
data() { return { arr: [1,3,2,5,11,10,20,50,6,8,7,4,9] } }, mounted() { this.arr.sort(this.cmp)//注意此处不能使用 this.cmp()。原因 1:代码会报错 2.我们需要的是传入一个函数 this.cmp,this.cmp()这样只会得到 a-b 值 }, methods: { cmp: function(a, b) { return a - b } },
控制台如下:
完成排序!
如果小伙伴需要 降序 排列,只需将 自定义比较函数
return a - b 改为 b - a 即可!~
参考博客:https://blog.csdn.net/baidu_25343343/article/details/54982747
原文:https://www.cnblogs.com/langxiyu/p/10912377.html