iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
JavaScript

React30——用 React 探索 JavaScript30 的魅力系列 第 14

[Day14]_JavaScript-References-VS-Copying

  • 分享至 

  • xImage
  •  

Day14 要來學習怎麼複製資料

Q1

  • 基本型別是 call by value ,所以不會更改到原始資料
        let age = 100;
        let age2 = age;
        age = 200;

Q2

  • 字串也是基本型別
        let name = "Wes";
        let name2 = name;
        name = "wesley";

Q3

  • 陣列是 call by reference,teamplayers 指向相同,所以會更動到原始的陣列
        const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
        const team: string[] = players;
        team[3] = "Lux";

Q4

  • slice() 會回傳新的陣列,所以不會更動到原始資料
        const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
        const team2: string[] = players.slice();
        team2[3] = "Copy 1";

Q5

  • 先建立空的陣列,再用 concat() 連接起來也可以複製陣列
        const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
        const team3: string[] = ([] as string[]).concat(players);
        team3[3] = "Copy 2";

Q6

  • 展開運算子可以複製陣列
        const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
        const team4: string[] = [...players];
        team4[3] = "Copy 3";

Q7

  • Array.from() 可以複製陣列
        const players: string[] = ["Wes", "Sarah", "Ryan", "Poppy"];
        const team5: string[] = Array.from(players);
        team5[3] = "Copy 4";

Q8

  • 物件的複製可以用 Object.assign() 來建立新的物件,然後用來包裝原始資料與新的資料
        const person: Person = { name: "Wes Bos", age: 80 };
        const cap2: Person = Object.assign({}, person, { number: 99, age: 12 });

Q9

  • 如果要複製很多層的資料可以使用 JSON.parse(JSON.stringify(data)
        const wes: Wes = {
          name: "Wes",
          age: 100,
          social: {
            twitter: "@wesbos",
            facebook: "wesbos.developer",
          },
        };
        const dev2: Wes = JSON.parse(JSON.stringify(wes));
        dev2.social.twitter = "@wesdev";

DEMO

https://codesandbox.io/p/devbox/day14-javascript-references-vs-copying-7gtntz


上一篇
[Day13]_Slide-in-on-Scroll
下一篇
[Day15]_LocalStorage
系列文
React30——用 React 探索 JavaScript30 的魅力30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言