JS30-14-JavaScript-References-VS-Copying

陣列與物件的傳址(reference)複製(Copying)

目標

  • 了解陣列與物件的傳址(reference)複製(Copying)

成品

[GitHub]


JS學習紀錄

型別介紹

基本型別:string、number、boolean、null、undefined
除了以上幾種之外,其他都可以歸類至物件型別 (Object)

基本型別 => 傳值(value)
物件型別 => 傳址(reference)

陣列複製

列出可完成陣列複製的方式

  • Array.prototype.Slice()

    1
    2
    const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
    const team2 = players.slice();
  • Array.prototype.concat()

    1
    2
    const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
    const team3 = [].concat(players);
  • ES6 展開運算子( Spread Operator )

    1
    2
    const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
    const team4 = [...players];
  • Array.from()

    1
    2
    const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
    const team5 = Array.from(players);

物件複製

列出可完成物件複製的方式,以及有雷的地方。

  • Object.assign()

    淺拷貝
    1
    2
    3
    4
    5
    6
    const person = {
    name: 'Wes Bos',
    age: 80
    };

    const cap2 = Object.assign({}, person);
  • JSON.parse() & JSON.stringify()

    JSON轉換
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    const wes = {
    name: 'Wes',
    age: 100,
    social: {
    twitter: '@wesbos',
    facebook: 'wesbos.developer'
    }
    };

    // Object.assign 只能淺複製一層,若第二層以上依舊是 傳址(reference)
    const dev = Object.assign({}, wes);

    // 透過JSON轉字串後,利用傳值的特性複製給新變數後,然後轉回物件型態,達到可複製二層以上的物件。
    const dev2 = JSON.parse(JSON.stringify(wes));

特例:
function 沒辦法轉成 JSON 再轉回來,複製的function會直接消失

JSON轉換失敗案例
1
2
3
4
5
6
7
8
9
var obj1 = {
fun: function(){
console.log(123)
}
};
var obj2 = JSON.parse(JSON.stringify(obj1));

console.log(typeof obj1.fun); // 'function'
console.log(typeof obj2.fun); // 'undefined' <-- 沒複製