Akiq2016/blog

JSON.stringify()

Opened this issue · 0 comments

奇淫技巧

有个面试题 - 实现一个remove函数,删除对象属性,有这样的方法

var test1 = {
  a: 123,
  b: 'bbb',
  c: false
}
// 删除属性
test1.b = undefined
JSON.parse(JSON.stringify(test1))

console.log(test1) // {a: 123, c: false}

引申分析 - JSON的值类型

在 JSON 的名称 - 值对中,值可以是字符串、数字、对象、数组、布尔值、null。

value

引申分析 - JSON.stringify(value[,replacer[,space]]) - value

The undefined value is not rendered.
The null value is rendered in JSON text as the String null.
The true value is rendered in JSON text as the String true.
The false value is rendered in JSON text as the String false.
  1. NaN || Infinity 将被显示为 String null.
  2. 其他的非JSON值类型(例如undefined、function)将不会生成字符串,而是生成了undefined。
    • 在数组中,这类值最终显示为String null。
    • 在对象中,拥有这类值的属性最终将被排除在被序列化的字符串外。
JSON.stringify(NaN)
// "null"

JSON.stringify(Infinity)
// "null"

JSON.stringify(undefined)
// undefined

JSON.stringify(function () {})
// undefined

JSON.stringify([ function(){} ])
// "[null]"

JSON.stringify({ a:  function(){} })
// "{}"

总结

因此,假如存在对象a如下,序列化后得到"{"a":null,"b":null}",也可以理解其中的缘由惹。同时也可以发现,本笔记开头的面试题JSON.parse(JSON.stringify())这种删除属性的方法,是存在坑的,需要根据实际场景谨慎使用。

var a = {
  a: NaN,
  b: Infinity,
  c: undefined,
  d: function() {}
}

JSON.stringify(a)
// "{"a":null,"b":null}"

学习资料

JSON
Ecma-262