0%

[Day26] jsES6語法-解構(上)

我們可以使用解構的方式,將右邊的值給映射到左邊,比如將 family 的值映射到變數 ming,father,mother 裡面。

1
2
3
let family = ['小明','爸爸','媽媽'];
let [ming,father,mother] = family
console.log(ming,father,mother)

我們也可以用這種方式來交換數值,而不用像先前一樣多宣告一個變數來交換值。

1
2
3
4
let mother = '媽媽';
let father = '爸爸';
[mother,father] = [father,mother];
console.log(mother,father);

我們也可以直接使用解構的方式,將 str 字串的值給取出來,映射到 a b c 變數中。

1
2
3
let str = '你好嗎';
let [a,b,c] = str;
console.log(a,b,c)