zoukankan      html  css  js  c++  java
  • json 数据 添加 删除 排序

    js数据格式和json数据格式,各有各的用处,就个人而言,json更好用一点,js自身的数组和对像限制比较多。

    以js的数组举例:

    1. var a = ['1'];  
    2. a[5] = 52;  
    3. a.length    //这儿的结果是6,也就是说,中间的key会自动补全,而值呢,是undefined  

    一,添加和删除

    1,一维数组

    1. test = {};                      //空json对像  
    2. test['firstname'] = "tank";     //添加二个元素  
    3. test['lastname'] = "zhang";  
    4. console.log(test);              //查看  
    5.   
    6. delete test['lastname'];        //删除json中的某个元素  
    7. console.log(test);  

    2,二维数组

    1. test1 = [{"name":"tank","total":"100"},{"name":"zhang","total":"23"},{"name":"hao","total":"325"}];  
    2. add = {"name":"may"};  
    3.   
    4. test1.push(add);              //添加一个元素  
    5. console.log(test1);    
    6.   
    7. delete test1[2];              //删除一个元素  
    8. console.log(test1);  

    二,排序

    1,一维数组

    1. test = ["100","23","325"];           //定义个数组  
    2.   
    3. function sortNumber(a,b)             //定义排序方法  
    4. {  
    5.      return a - b  
    6. }  
    7.   
    8. test1_sort=test.sort(sortNumber);  
    9.   
    10. console.log(test1_sort);  

    2,二维数组

    1. test1 = [{"name":"tank","total":"100"},{"name":"zhang","total":"23"},{"name":"hao","total":"325"}];  
    2.   
    3. sort_by = function(field, reverse, primer){         //定义排序方法  
    4.   
    5.    var key = primer ?  
    6.        function(x) {return primer(x[field])} :  
    7.        function(x) {return x[field]};  
    8.   
    9.    reverse = [-1, 1][+!!reverse];  
    10.   
    11.    return function (a, b) {  
    12.        return a = key(a), b = key(b), reverse * ((a > b) - (b > a));  
    13.      }   
    14.   
    15. }  
    16.   
    17. test1_sort=test1.sort(sort_by('total', true, parseInt));    //根据total,升序排  
    18. console.log(test1_sort);   
    19.   
    20. test1_sort=test1.sort(sort_by('name', false, ''));          //根据name,倒序排  
    21. console.log(test1_sort);  
  • 相关阅读:
    站点防攻击之禁止国外ip
    docker 安装rabbitMQ
    【转】浅析支付系统的整体架构
    【转】MQ详解及四大MQ比较
    SQL server 中的dbo、guest
    网站加载速度的优化(1):优化前端页面
    【转】Apache ab压力测试
    Asp.Net Core 部署发布后EFCore数据库断连和Google浏览器无法存储Cookie
    C# 使用nuget.exe发布类库及更新类库
    .net core 读取Excal文件数据及注意事项
  • 原文地址:https://www.cnblogs.com/Hobin/p/5193053.html
Copyright © 2011-2022 走看看