日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

前端的多種克隆方式和注意事項(xiàng)

作者:qq_42750608 更新時(shí)間: 2023-10-10 編程語言

克隆的意義和常見場景:

  1. 意義: 保證原數(shù)據(jù)的完整性和獨(dú)立性
  2. 常見場景: 復(fù)制數(shù)據(jù), 函數(shù)入?yún)? class構(gòu)造函數(shù)等

淺克隆:

對象常用的淺克隆

  1. es6擴(kuò)展運(yùn)算符...
  2. Object.assign

數(shù)組常用的淺克隆

  1. es6的擴(kuò)展運(yùn)算符...
  2. slice=>arr.slice(0)
  3. [].concat

深度克隆:

  1. 克隆對象的每個(gè)層級
  2. 如果屬性值是原始數(shù)據(jù)類型, 拷貝其值, 也就是我們常說的值拷貝
  3. 如果屬性值是引用類型, 遞歸克隆

深度克隆的方法:

JSON.stringify+JSON.parse

eg:JSON.parse(JSON.stringify(對象或數(shù)組))

JSON.stringify+JSON.parse的局限性:

  1. 只能復(fù)制普通鍵的屬性, symbol類型的無能為力
  2. 循環(huán)引用對象,比如window不能復(fù)制
  3. 函數(shù),Date,Reg,Blob等類型不能復(fù)制
  4. 性能差

消息通訊 --BroadcastChannel等等

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)
})

消息通訊:

  1. window.postMessage
  2. BroadcastChannel
  3. Shared Worker
  4. Message Channel

基于消息通訊的局限:

  1. 循環(huán)引用對象不能復(fù)制, 如:windows
  2. 函數(shù)不能復(fù)制
  3. 同步變成異步

手寫深度克隆--遞歸

function arrLengthMoreThanZero(val) {
       return Array.isArray(val) && val.length > 0
    }
    // 非空對象或者數(shù)組length大于0的數(shù)組
    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
        }
        // 初始化返回結(jié)果
        let result;
        // instance of判斷是不是數(shù)組
        if(obj instanceof Array) {
            result = []
        }
        else {
            result = {}
        }
        // for in循環(huán)對象和數(shù)組都能使用
        for(let key in obj) {
            // hasOwnProperty=>保證key不是原型的屬性
            if(obj.hasOwnProperty(key)) {
                // 遞歸
                result[key] = deepClone(obj[key])
            }
        }
        return result
    }

原文鏈接:https://blog.csdn.net/qq_42750608/article/details/133362971

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新