美文网首页
数组及数组对象排序方法

数组及数组对象排序方法

作者: Ashinluo要进步 | 来源:发表于2019-08-28 01:19 被阅读0次

    //数组方法排序:

    function sortNumber(a, b) {

    return a - b;

    }

    //数组对象方法排序:

    function sortByKey(array, key) {

    return array.sort(function(a, b) {

    var x = a[key];

    var y = b[key];

    return x < y ? -1 : x > y ? 1 : 0;

    });

    }

    在vue中使用例子:

    HTML部分:

    <ul>

    <li v-for="item in sortItems">{{ item }}</li>

    </ul>

    <ul v-for="item in sortVe">

    <li >{{item.value}}-{{item.ve}}</li>

    </ul>

    js部分:

    data: {

    items: [20, 23, 18, 65, 32, 19, 54, 56, 41],

    s:[

    {value:'A',ve:'2'},

    {value:'s',ve:'3'},

    {value:'h',ve:'1'},

    {value:'i',ve:'5'},

    {value:'n',ve:'4'},

    ]

    },

    // vue低版本中 data里面的items和computed里面可以一样,但是高版本,是不允许相同名称

    computed: {

    sortItems: function() {

    return this.items.sort(sortNumber);

    },

    sortVe:function(){

    return sortByKey(this.s,'ve')

    }

    }

    相关文章

      网友评论

          本文标题:数组及数组对象排序方法

          本文链接:https://www.haomeiwen.com/subject/bnsuectx.html