一、JSON 序列化和反序列化
对于一般(狭义)的对象,最简单快速的方法就是使用 JSON 的序列化和反序列化:
const o1 = {
name: 'xxx',
age: 18,
child: {
name: 'zzz'
}
}
const o2 = JSON.parse(JSON.stringify(o1))
o1 === o2 // false
o1.name === o2.name // true
o1.child === o2.child // false
o1.child.name === o2.child.name // true
缺点:仅支持 JSON 所支持的数据类型和结构。
例如:
- 不支持函数,会被直接忽略
- 不支持 undefined,会被直接忽略
- 不支持循环引用,例如 xxx.self = xxx,会报错
对于更复杂的对象,就无法使用上面的办法,需要使用递归来进行深拷贝。
二、搭建测试环境
安装 mocha、chai 和 sinon-chai:
yarn init -y
yarn add mocha chai sinon-chai --dev
package.json 添加运行测试命令:
"scripts": {
"test": "mocha test/**/*.js"
}
导出 deepClone:
// src/index.js
function deepClone() {}
module.exports = deepClone
编写测试用例:
// test/index.js
const chai = require('chai')
const sinonChai = require('sinon-chai')
const deepClone = require('../src/index')
chai.use(sinonChai)
const assert = chai.assert
describe('测试深拷贝', () => {
it('成功引入深拷贝', () => {
assert.isFunction(deepClone)
})
})
运行测试:
yarn test
三、递归深拷贝
1、拷贝基本类型
添加测试用例:
it('拷贝基本类型', () => {
const s1 = 'xxx'
const n1 = 123
const u1 = undefined
const b1 = true
const empty1 = null
const s2 = deepClone(s1)
const n2 = deepClone(n1)
const u2 = deepClone(u1)
const b2 = deepClone(b1)
const empty2 = deepClone(empty1)
assert(s2 === s1)
assert(n2 === n1)