搜尋
首頁web前端前端問答es6中assign的用法是什麼

在es6中,assign用於物件的合併,可以將來源物件的所有可枚舉屬性複製到目標物件;若目標物件與來源物件有同名屬性,或多個來源物件有同名屬性,則後面的屬性會覆寫前面的屬性,語法為「Object.assign(...)」

es6中assign的用法是什麼

#本教學操作環境:windows10系統、ECMAScript 6.0版、Dell G3電腦。

es6中assign的用法是什麼

Object.assign方法用於物件的合併,將來源物件(source)的所有的可列舉屬性(key:value)複製到目標物件(target)

例如:

        const target = { a : 1 };
        const  source1 = { b: 2 };
        const  source2 = { c: 3 };
Object.assign(target,source1,source2)      // target { a:1, b:2, c:3 }

注意: 如果目標物件與來源物件有同名屬性,或多個來源物件有同名屬性,則後面的屬性會覆寫前面的屬性。

例如:

    const target  = {a:1,b:1};
    const source1 = { b: 2,c:2};
    const source2 = {c:3};
 Object.assign(target,source1,source2); // target {a:1,b:2,c:3}

如果只有一個參數,Object.assign會直接返回改參數,如果參數不是對象則會先轉出對象,然後在返回,由於null 與undefined 無法轉換為對象,所以如果他們作為參數就會報錯。如果非物件參數出現在來源物件的位置(意思是不是第一個參數),那麼處理規則就會有所不同。首先,這些參數都會轉換成對象,如果出現null 或undefined只要保證不再首個參數就不會報錯。

例如:

   const obj = {a:1},
   Object.assign(obj)  === obj   // true   
   typeof  Object.assign(2)    // object
   Object.assign(undefined)  // 报错
   Object.assign(null)   // 报错
   Object.assign(obj,undefined)

其他類型的值(即數值、字串和布林值)不在首參數,也不會報錯,但是字串會以數組的形式,拷貝入目標對象,其他值都不會產生效果。

    const v1 = 'abc';
    const v2 = true;
    const v3 = 10;
    const objCurrent = Object.assign({},v1,v2,v3);  // {0:'a',1:'b',2:'c'}; 
    // 上面代码中,v1,v2,v3分别是字符串、布尔值、数值,结果只有字符串符合目标对象(以字符串数组的形式),数值与布尔值都会被忽略。这是因为只有字符串的包装对象,会产生枚举属性。
Object.assign()的深浅拷贝问题
    const obj1 = {a: 1};
    const obj2 = {b: 2};
    const obj3 = {c: 3};
    const obj = Object.assign(obj1,obj2,obj3);
    console.log(obj);   //  {a:1,b:2,c:3}
    console.log(obj1);   //   {a:1,b:2,c:3}  原始对象也被改变啦
    const v1 ={a:1},
    const currentObj = Object.assign(JSON.parse(JSON.stringify(v1)),{e:2})
    console.log(currentObj)  // {a:1,e:2}
    console.log(v1) // {a:1} 并没有发生变化

當物件中只有一級屬性,沒有二級屬性的時候,此方法為深拷貝,但是物件中有物件的時候,此方法在二級屬性以後就是淺拷貝。

使用遞歸的方式實作深拷貝

    // _deep 深度拷贝的方法
    function  _deep(source){
        let  target;
        if (typeof source === 'object'){
            // 判断目标值是数组还是对象
            target = Array.isArray(source) ? []: {}
            for (let key in source) {
                // 指示对象自身属性中是否含有指定的属性
                if(source.hasOwnProperty[key]){
                      // 如果属性不是对象则赋值,负责递归
                      if(typeof source[key] !== 'object'){
                            target[key] = source[key]
                      }else {
                            target[key] = _deep(source[key])
                      }
                }
            }
        } else {
           target = source
        }
        // 返回目标值
        return  target 
    }

使用js實作深拷貝

    function _deepJs(_data){
        return JSON.parse(JSON.stringify(_data));
    }

【相關推薦:javascript影片教學web前端

以上是es6中assign的用法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
反應的局限性是什麼?反應的局限性是什麼?May 02, 2025 am 12:26 AM

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潛在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

React的學習曲線:新開發人員的挑戰React的學習曲線:新開發人員的挑戰May 02, 2025 am 12:24 AM

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

為React中的動態列表生成穩定且獨特的鍵為React中的動態列表生成穩定且獨特的鍵May 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript疲勞:與React及其工具保持最新JavaScript疲勞:與React及其工具保持最新May 02, 2025 am 12:19 AM

javascriptfatigueinrectismanagbaiblewithstrategiesLike just just in-timelearninganning and CuratedInformationsources.1)學習whatyouneedwhenyouneedit

使用USESTATE()掛鉤的測試組件使用USESTATE()掛鉤的測試組件May 02, 2025 am 12:13 AM

tateractComponents通過theusestatehook,使用jestandReaCtTestingLibraryToSigulationsimintionsandIntractions and verifyStateChangesInTheUI.1)underthecomponentAndComponentAndComponentAndConconentAndCheckInitialState.2)模擬useruseruserusertactionslikeclicksorformsorformsormissions.3)

React中的鑰匙:深入研究性能優化技術React中的鑰匙:深入研究性能優化技術May 01, 2025 am 12:25 AM

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndi​​cesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

反應中的鍵是什麼?反應中的鍵是什麼?May 01, 2025 am 12:25 AM

ReactKeySareUniqueIdentifiers usedwhenrenderingListstoimprovereConciliation效率。 1)heelPreactrackChangesInListItems,2)使用StableanDuniqueIdentifiersLikeItifiersLikeItemidSisRecumended,3)避免使用ArrayIndi​​cesaskeyindicesaskeystopreventopReventOpReventSissUseSuseSuseWithReRefers和4)

反應中獨特鍵的重要性:避免常見的陷阱反應中獨特鍵的重要性:避免常見的陷阱May 01, 2025 am 12:19 AM

獨特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndi​​ceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用