• JSON.stringify()的深度使用


    在使用JSON.stringify()对JSON数据进行序列化时

    1> 如果里面的属性是function,则会被忽略

    const data = {
         a: 'a',
         fn: funciton() {
               return true   
          }   
    }
    
    JSON.stringify(data); // "{"a":"a"}"    *******fn属性被忽略了**********

    2> 如果里面的属性的值是undefined, 也是会被忽略的

    const data = {
         a: 'a',
         b: undefined
    }
    
    JSON.stringify(data); // "{"a":"a"}"    *******b属性被忽略了**********

    3>但是如果里面的属性值是null, 是不会被忽略的

    const data = {
         a: 'a',
         b: null
    }
    
    JSON.stringify(data); // "{"a":"a","b":null}"    *******b属性没有被忽略**********

    其实JSON.stringify()有三个参数:stringify(value, [replacer, space](可选的, replacer: 自定义的函数,space: 格式化输出(相当于tab键,值的范围是[1(负数的时候默认是1),10]))),为了属性值为function和undefined的属性在序列化的时候不要被忽略,我们可以对replacer做以下操作

    比如:

    const replace = function(k, v) {
       if(v === undefined) {
        return 'undefined';
       }
    if(typeof v === 'function') {  return Function.prototype.toString.call(v); } return v; } JSON.stringify(data, replace); //"{"a":"a","c":"undefined","b":"function () {         return true;    }"}"

    ************注意************

    自定义对象属性的时候, 尽量不要定义toJSON方法,原因如下:

    const data = {
         a: 'a',
         toJSON: function() {
             return true;
        }
    }
    JSON.stringify(data); //"true"  (toJSON会把其他的属性都覆盖掉)
  • 相关阅读:
    ACE-6.1.0 linux 下的编译与安装步骤
    tcp_sync_server and tcp_sync_client
    网络服务器操作命令telnet
    eclipse CDT unresolved inclusion
    qt安装--this Qt version uses an unsupported makefile
    java指令详解
    (8) tomcat中管理领域、角色及用户
    (7) 将tomcat HTTP连接器启动在80端口(jsvc使用详解)
    10月16日面试总结
    MYSQL查询的四种情况
  • 原文地址:https://www.cnblogs.com/yyh1/p/7246490.html
Copyright © 2020-2023  润新知