Bootstrap

js 简单模拟JSON.stringify 功能

作用:序列化成 一个 JSON 字符串的值

function stringifyJSON(value) {
    if (typeof value === "string") {
      //处理\和",加上""
      return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
    }
    if (typeof value === "boolean") {
      return value.toString();
    }
    if (typeof value === "number") {
    	//typeof value === "bigint" 无法序列化,返回'null'
      //如果参数是 NaN,正无穷大或者负无穷大,会返回false
      return isFinite(value) ? value.toString() : "null";
    }
    if (Array.isArray(value)) {
      const arrayStr = value.map((item) => stringifyJSON(item)).join(",");
      //加上[]
      return `[${arrayStr}]`;
    }
    if (typeof value === "object") {
      //null 类型也是 object
      if (value === null) {
        return "null";
      }
      //对象所有key
      const keys = Object.keys(value);
      const objectStr = keys
        .map((key) => {
          //值stringifyJSON
          const val = stringifyJSON(value[key]);
          //重新组合,key加上""
          return `"${key}":${val}`;
        })
        .join(",");
      //加上{}
      return `{${objectStr}}`;
    }
    //undefined,symbol,bigint
    return "null";
  }

使用示例

const obj = {
    name: "小米",
    money: 2000,
    isSale: false,
    type: ["note1", "note2"],
    address: null,
    chip:undefined,
    getMoney: function () {
      return this.name;
    },
  };
  console.log("obj1", stringifyJSON(obj));
  //数组,undefined、任意的函数以及symbol值在序列化的过程中会被转换成 null
  //非数组,undefined、任意的函数以及symbol值在序列化的过程中会被忽略
  console.log("obj2", JSON.stringify(obj));

具体,参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

;