高级前端
js
【Q148】关于 JSON,以下代码输出什么

关于 JSON,以下代码输出什么

更多描述

const obj = {
  a: 3,
  b: 4,
  c: null,
  d: undefined,
  get e() {},
};
 
console.log(JSON.stringify(obj));

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 149 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

const obj = {
  a: 3,
  b: 4,
  c: null,
  d: undefined,
  get e() {},
};

console.log(JSON.stringify(obj))

输出什么?

{"a":3,"b":4,"c":null}

对其中的 undefinedfunction 将在 JSON.stringify 时会忽略掉

Author 回答者: qiushangzhe (opens in a new tab)

666

const obj = {
  a: 3,
  b: 4,
  c: null,
  d: undefined,
  get e() {},
};

console.log(JSON.stringify(obj)) 输出什么?

{"a":3,"b":4,"c":null}

对其中的 undefinedfunction 将在 JSON.stringify 时会忽略掉

const obj 中的 get e () {} 并不是函数,此处应该是重写了 obj.eget 方法,因为 get 方法未定义返回值,因此在执行 JSON.stringify 时,执行 obj.eget 方法,返回 undefined,因此被忽略

让我们更改 get 方法的返回值 image

看到 666 了吧?

Author 回答者: Awalter0411 (opens in a new tab)

const obj = {
  a: 3,
  b: 4,
  c: null,
  d: undefined,
  get e() {},
};

console.log(JSON.stringify(obj)) 输出什么?

{"a":3,"b":4,"c":null}

对其中的 undefinedfunction 将在 JSON.stringify 时会忽略掉

const obj 中的 get e () {} 并不是函数,此处应该是重写了 obj.eget 方法,因为 get 方法未定义返回值,因此在执行 JSON.stringify 时,执行 obj.eget 方法,返回 undefined,因此被忽略

让我们更改 get 方法的返回值 image

看到 666 了吧?

原来是这样,又学到了