縮寫在撰寫 vue 的時候很常用到,來記錄一下。
物件的縮寫
下方有兩個物件資料,想要把兩個物件合併可以怎麼寫?
1 2 3 4 5 6
| const one = 1; const numbers = { two: 2, three: 3, four: 4, };
|
傳統的寫法會是在新宣告一個變數中,命名一個相同的名字,並把對應的變數名稱也放入物件中的值,程式碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| let one = 1; let numbers = { two: 2, three: 3, four: 4, };
let newObj = { one: one, numbers: numbers, }; console.log(newObj);
|
ES6 中如果屬性與之前相符,就可以省略值的內容,就可以變這樣寫:
1 2 3 4 5 6 7 8 9 10 11 12
| let one = 1; let numbers = { two: 2, three: 3, four: 4, };
let newObj = { one, numbers, }; console.log(newObj);
|
物件函式的縮寫
原物件函式如下:
1 2 3 4 5
| const newObj = { shortfun: function () { console.log("I am a function"); }, };
|
縮寫後:
1 2 3 4 5
| const newObj = { shortfun() { console.log("I am a function"); }, };
|
此縮寫與箭頭函式結果是不同的,不可亂用。
搭配解構賦值使用縮寫
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const team = { teamA: { name: "mike", }, teamB: { name: "alex", }, teamC: { name: "johnson", }, };
const newTeam = { ...team, }; newTeam.shoot = "pippen";
console.log(newTeam, team);
|