国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語(yǔ)言 > JavaScript > 正文

javascript對(duì)JSON數(shù)據(jù)排序的3個(gè)例子

2024-05-06 16:04:03
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
這篇文章主要介紹了javascript對(duì)JSON數(shù)據(jù)排序的3個(gè)例子的相關(guān)資料

一、適用于數(shù)字排序和字幕排序
json 的排序方法有很多種,這是其中最簡(jiǎn)單的一種方法。

復(fù)制代碼 代碼如下:


var sortBy = function (filed, rev, primer) {
    rev = (rev) ? -1 : 1;
    return function (a, b) {
        a = a[filed];
        b = b[filed];
        if (typeof (primer) != 'undefined') {
            a = primer(a);
            b = primer(b);
        }
        if (a < b) { return rev * -1; }
        if (a > b) { return rev * 1; }
        return 1;
    }
};
var obj = [
    {b: '3', c: 'c'},
    {b: '1', c: 'a'},
    {b: '2', c: 'b'}
];


1、數(shù)字排序

復(fù)制代碼 代碼如下:

obj.sort(sortBy('b', false, parseInt));
console.log(obj);


2、字符串排序

復(fù)制代碼 代碼如下:

obj.sort(sortBy('b', false, String));
console.log(obj);


二、JSON排序例子2

復(fù)制代碼 代碼如下:


var willSort = [
    {
        name:'shangwenhe',
        age:25,
        height:170
    },
    {
        name:'zhangsan',
        age:31,
        height:169
    },
    {
        name:'lisi',
        age:31,
        height:167
    },
    {
        name:'zhaowu',
        age:22,
        height:160
    },
    {
        name:'wangliu',
        age:23,
        height:159
    }
];


/*
    @function     JsonSort 對(duì)json排序
    @param        json     用來(lái)排序的json
    @param        key      排序的鍵值
*/
function JsonSort(json,key){
    //console.log(json);
    for(var j=1,jl=json.length;j < jl;j++){
        var temp = json[j],
            val  = temp[key],
            i    = j-1;
        while(i >=0 && json[i][key]>val){
            json[i+1] = json[i];
            i = i-1;   
        }
        json[i+1] = temp;

    }
    //console.log(json);
    return json;

}
var json = JsonSort(willSort,'age');
console.log(json);

三、JSON排序例子3

復(fù)制代碼 代碼如下:


var people = [
{
    name: 'a75',
    item1: false,
    item2: false
},
{
    name: 'z32',
    item1: true,
    item2: false
},
{
    name: 'e77',
    item1: false,
    item2: false
}];

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));
    });
}

people = sortByKey(people, 'name');

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 凉山| 定兴县| 永修县| 台湾省| 阿克苏市| 电白县| 明水县| 应用必备| 鄄城县| 苗栗县| 永城市| 龙胜| 祁连县| 叶城县| 湾仔区| 格尔木市| 牟定县| 个旧市| 团风县| 合阳县| 潼南县| 开封市| 定结县| 哈巴河县| 新化县| 灌阳县| 贵港市| 双江| 庐江县| 加查县| 酒泉市| 乌拉特前旗| 兰溪市| 娄底市| 马尔康县| 凤翔县| 南雄市| 桦川县| 囊谦县| 丰镇市| 类乌齐县|