Json
json
JSON.stringify()
JSON.stringify(value[, replacer [, space]])
如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为 null 或者未提供,则对象所有的属性都会被序列化。
以下代码不会报错循环引用的值
let a = {}
a.c = a
const replacer = () => {
const cache = new WeakMap()
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (cache.has(value)) {
return `circle ${cache.get(value)}`
}
cache.set(value, key || 'root')
}
return value
}
}
function reviver2(key, value) {
if (typeof value === 'string' && value.includes('circle')) {
let tempkey = value.split(' ')[1]
if (tempkey === 'root') {
return this
} else {
return this[tempkey]
}
}
return value
}
let strB = JSON.stringify(a, replacer())
let copyB = JSON.parse(strB, reviver2)
深拷贝
1.JSON.parse(JSON.stringify(object))
- 会忽略 undefined
- 会忽略 symbol
- 不能序列化函数正则对象等特殊对象
- 不能处理指向相同引用的情况,相同的引用会被重复拷贝
let obj = {
reg: /^reg$/,
fun: function () {},
syb: Symbol('foo'),
undefined: undefined,
}
let copied_obj = JSON.parse(JSON.stringify(obj))
console.log(copied_obj) // { reg: {} }
2.递归拷⻉
function deepCopy(obj) {
return Reflect.ownKeys.reduce((pre, item) => {
if (typeof obj[item] !== 'object') {
pre[item] = deepCopy(obj[item])
} else {
pre[item] = obj[item]
}
return pre
}, {})
}