JSON.stringify+JSON.parse
eg:JSON.parse(JSON.stringify(对象或数组))
- let chId = 0
- function clone(data) {
- chId++
- let cname = `__clone__${chId}`
- let ch1 = new BroadcastChannel(cname)
- let ch2 = new BroadcastChannel(cname)
- return new Promise((resolve)=> {
- ch2.addEventListener('message', ev=>resolve(ev.data), {once: true});
- ch1.postMessage(data)
- })
- }
-
- clone({
- a: 'fdfewfjew',
- b: 1,
- // c: Symbol('gggg')
- })
- .then(res=> {
- console.log(res)
- })
- .catch(err=> {
- console.log(err)
- })
消息通讯:


手写深度克隆--递归
- function arrLengthMoreThanZero(val) {
- return Array.isArray(val) && val.length > 0
- }
- // 非空对象或者数组length大于0的数组
- function isNotNullObjectOrArr (val) {
- if(val == null) return false;
- const isObject = Object.prototype.toString.call(val) === '[object Object]'
- if(isObject && JSON.stringify(val) === '{}') return false;
- return Object.prototype.toString.call(val) === '[object Object]' || arrLengthMoreThanZero(val);
- }
- function deepClone(obj={}) {
- if(!isObject(obj)) {
- return obj
- }
- // 初始化返回结果
- let result;
- // instance of判断是不是数组
- if(obj instanceof Array) {
- result = []
- }
- else {
- result = {}
- }
- // for in循环对象和数组都能使用
- for(let key in obj) {
- // hasOwnProperty=>保证key不是原型的属性
- if(obj.hasOwnProperty(key)) {
- // 递归
- result[key] = deepClone(obj[key])
- }
- }
- return result
- }