2、JSON.stringify

JSON.stringify转换特点

参数为基础类型

  1. undefined类型返回undefined
  2. boolen类型返回"true"或者"false"
  3. number类型返回对应的字符串数值
  4. symbol类型返回undefined
  5. null类型返回"null"
  6. string类型返回string
  7. NaN和Infinity返回"null"

参数为引用类型

  1. function类型返回undefined
  2. Array类型,内部的undefined,function,symbol类型返回null
  3. RegExp类型,返回"{}"
  4. Date类型,返回(new Date).toJSON()
  5. object类型
    1. 返回toJSON()
    2. 忽略值为undefined,function,symbol的属性
    3. 忽略键为symbol的属性
    4. 循环引用报错

实现

function jsonStringify(data) {
  const type = typeof data;
  // 处理基础类型
  if (type !== "object") {
    const result = data;
    if (Number.isNaN(data) || data === Infinity) {
      return "null";
    } else if (["function", "undefined", "symbol"].includes(type)) {
      // function当做基础类型处理
      return undefined;
    } else if (type === "string") {
      return `"${data}"`;
    }
    return String(data)
  } else {
    // 处理引用类型
    // typeof null返回结果为 object
    if (data === null) {
      return "null";
    } else if (data.toJSON && typeof data.toJSON === "function") {
      // 递归处理嵌套toJSON的情况
      return jsonStringify(data.toJSON());
    } else if (data instanceof Array) {
      let result = [];
      data.forEach((item, index) => {
        if (["function", "undefined", "symbol"].includes(typeof item)) {
          result[index] = "null";
        } else {
          result[index] = jsonStringify(item);
        }
      });
      // 所有单引号要替换成双引号
      return `[${result}]`.replace(/'/g, '"');
    } else {
      // 处理普通对象
      let result = [];
      Object.keys(data).forEach((item, index) => {
        // 忽略key为symbol的属性
        if (typeof item !== "symbol") {
          // 忽略值为undefined,function,symbol的属性
          if (
            data[item] !== undefined &&
            typeof data[item] !== "function" &&
            typeof data[item] !== "symbol"
          ) {
            result.push(`"${item}":${jsonStringify(data[item])}`);
          }
        }
      });
      return `{${result}}`.replace(/'/g, '"');
    }
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54