Daily-Question icon indicating copy to clipboard operation
Daily-Question copied to clipboard

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

Open shfshanyue opened this issue 6 years ago • 4 comments

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

console.log(JSON.stringify(obj))

shfshanyue avatar Dec 27 '19 08:12 shfshanyue

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 时会忽略掉

shfshanyue avatar Dec 27 '19 08:12 shfshanyue

666

qiushangzhe avatar Dec 27 '19 08:12 qiushangzhe

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 了吧?

ghost avatar Aug 05 '20 16:08 ghost

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 了吧?

原来是这样,又学到了

ilukemagic avatar Aug 29 '22 07:08 ilukemagic