微信小程序——列表遍歷排序方法

Page({
    data: {
        arr: [
          { id: '1', name: '一', age: '12' },
          { id: '5', name: '五', age: '24' },
          { id: '3', name: '三', age: '28' },
          { id: '4', name: '四', age: '18' },
          { id: '2', name: '二', age: '36' },
        ],
    },
    mySort: function (e) {
        //property 根據什麼排序
        var property = e.currentTarget.dataset.property;
        var self = this;
        var arr = self.data.arr;
        var sortRule = true; // 正序倒序
        self.setData({
          arr: arr.sort(self.compare(property, sortRule))
        })
        //console.log(arr)
      },
    compare: function (property, bol) {
        return function (a, b) {
        var value1 = a[property];
        var value2 = b[property];
        if(bol){
          return value1 - value2;
        }else {
          return value2 - value1;
        }
      }
    },
})
<button bindtap="mySort" data-property="id">根據id排序</button>
<button bindtap="mySort" data-property="age">根據年齡排序</button>
<view wx:for="{{arr}}" wx:key="id" wx:for-item="item" data-id="{{item.id}}">
    <view>{{item.name}}</view>
</view>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章