Javascript小型專案練習16 JavaScript References VS Copying(JS30-14)

JS30~這次的主題探討到幾個JS初學者常常不理解的部分,像是call by references & call by value的差別、淺層複製與深層複製(deep clone)的議題,算是個不錯的基礎複習!

HTML

//none

CSS

 //none

Javascript

    // start with strings, numbers and booleans
    let name = 'Danny'
    let name2 = name
    console.log(name, name2);
    name2 = 'John'
    console.log(name, name2);

    // Let's say we have an array
    // console.clear()
    const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
    // let players2 = players
    // players2[3] = 'Danny'
    // console.log("players are", players);
    // console.log("players2 are", players2);

    // and we want to make a copy of it.
    console.clear()
    let players3 = players.slice()
    players3[3] = 'Danny'
    console.log("players are", players);
    console.log("players3 are", players3);

    // or create a new array and concat the old one in
    let players4 = [].concat(players)
    players4[3] = 'DannyS'
    console.log("players are", players);
    console.log("players4 are", players4);

    // or use the new ES6 Spread
    let players5 = [...players]
    players5[3] = 'DannyW'
    console.log("players are", players);
    console.log("players5 are", players5);

    // The same thing goes for objects, let's say we have a person object

    // with Objects
    const person = {
      name: 'Wes Bos',
      age: 80
    };

    // and think we make a copy:
    let person2 = Object.assign({}, person)
    person2.age = 75;
    console.clear()
    console.log(person);
    console.log(person2);

    // Things to note - this is only 1 level deep - both for Arrays and Objects. lodash has a cloneDeep method, but you should think twice before using it.

    const student = {
      name: "danny",
      id: '9831032',
      social: {
        facebook: 'dannywang@facebook',
        twitter: 'danny@twitter'
      }
    }

    let student2 = Object.assign({}, student)
    student2.social.facebook = 'John@facebook'

    console.log(student);
    console.log(student2);

    let student3 = JSON.parse(JSON.stringify(student))
    student3.social.facebook = 'SWITH@facebook'

    console.log(student);
    console.log(student3); 

 

學習重點

  • 複習call by reference & call by value的概念,call by value只發生在primitive type的變數上(null,undefined,String,Boolean,Number)
  • 複習物件的複製方式
  • 了解如何簡單的做出深層複製的效果,但要思考是否真有這必要做深層複製

發表留言