0%

JS 筆記 - ES6:縮寫用法

ES6

縮寫在撰寫 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);
//one: 1
//numbers: {two: 2, three: 3, four: 4}

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";
//teamA: {name: "mike"}
//teamB: {name: "alex"}
//teamC: {name: "johnson"}
//shoot: "pippen"

console.log(newTeam, team);
//teamA: {name: "mike"}
//teamB: {name: "alex"}
//teamC: {name: "johnson"}