今天看了掘金上的一篇讲JSON.Stringify的文章学到了新知识
-
JSON.Stringify 可选参数有3个: value, replacer, space
-
a ?? b逻辑运算符 (ES11)当
a为undefined或null返回b, 其他都返回a -
关于参数replacer
const obj = { a: 1, b: 2, c: 'cc', d: undefined };
const replacer = (key, value) =>
typeof value === "number" ? value : undefined;
console.log(JSON.stringify(obj, replacer));
本以为结果'{'a': 1, 'b': 2}',然而返回的是undefined, 为什么会这样呢? 翻阅了一下 MDN
replacer 参数可以是一个函数或者一个数组。作为函数,它有两个参数,键(key)和值(value),它们都会被序列化。
在开始时,
replacer函数会被传入一个空字符串作为key值,代表着要被stringify的这个对象。随后每个对象或数组上的属性会被依次传入。
所以replacer第一次执行的时候,是需要返回整个对象的,否则无法继续执行下去, 因此需要加一个判断
const replacer = (key, value) =>
!key || typeof value === "number" ? value : undefined;