zoukankan      html  css  js  c++  java
  • 对象形式数组如何排序

    先直接给上方法:

         sortByKey:function(arr,key){
            return arr.sort(function(a,b){
              var x = a[key];
              var y = b[key];
              return ((x<y) ? -1 : ((x>y) ? 1 : 0))
            })
          }  
    

        这里我是在vue项目中用到的 ,其实什么项目中都是可以这么用的

    结构:

        <ul>
          <li v-for="kid in kids" >{{kid.name}}-{{kid.age}}</li>
        </ul>
    

      初始数据:

        data() {
          return {
            kids:[
              {
                name:"a",
                age:25
              },
              {
                name:"b",
                age:20
              },
              {
                name:"c",
                age:15
              },
              {
                name:"d",
                age:5
              }
            ]
          }
        },
    

      结果:

    要求按年龄从小到大排序:

    methods方法:

        methods:{
          sortByKey:function(arr,key){
            return arr.sort(function(a,b){
              var x = a[key];
              var y = b[key];
              return ((x<y) ? -1 : ((x>y) ? 1 : 0))
            })
          }
        }
    

      computed算法:

         newKids:function(){
            return this.sortByKey(this.kids,'age')
          }
    

      然后 注意要改掉循环中的主循环体是newKids,即:

        <ul>
          <li v-for="kid in newKids" >{{child.name}}-{{child.age}}</li>
        </ul>
    

      结果就是:

    另:return a-b 可以决定升降序

    function sort(a,b){
      return a-b  
    }
    

      

  • 相关阅读:
    android kl文件
    ELF文件结构描述
    jquery开头
    win7无声音显示“未插入扬声器或耳机” 怎么解决
    xhtml头文件设置
    break和continue的区别
    php目录函数
    mysql语法
    php中怎么导入自己写的类
    截取文件后缀名
  • 原文地址:https://www.cnblogs.com/ly-qingqiu/p/10956063.html
Copyright © 2011-2022 走看看