寫JS的時候,常常要從物件或陣列裡「取出值」,或是把幾個陣列、物件「合在一起」,ES6 新增的解構賦值(destructuring assignment)和展開運算子(spread operator ...)就是來解決這些麻煩事,讓程式更簡潔好讀
過去要取陣列裡的值如下:
const fruits = ['apple', 'banana', 'cherry'];
const first = fruits[0];
const second = fruits[1];
console.log(first, second);
有了解構賦值就可以這樣:
const [first, second] = ['apple', 'banana', 'cherry'];
console.log(first); // apple
console.log(second); // banana
還可以用逗號跳過值、設定預設值:
const [a, , c = 'default'] = ['A', 'B'];
console.log(a, c); // A default
物件也能直接「拆」
範例:
const user = { name: 'Alice', age: 25 };
const { name, age } = user;
console.log(name); // Alice
console.log(age); // 25
改變變數名稱
範例:
const { name: userName } = user;
console.log(userName); // Alice
搭配預設值
範例:
const { gender = 'female' } = user;
console.log(gender); // female
拿來處理函式參數不需要再寫user.name
、user.age
來呼叫
範例:
function printUser({ name, age }) {
console.log(`${name} is ${age} years old`);
}
const user = { name: 'Bob', age: 30 };
printUser(user); // Bob is 30 years old
展開運算子有兩個常用到的狀況
const arr1 = [1,2,3];
const arr2 = [4,5];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // [1,2,3,4,5]
const obj1 = {a:1, b:2};
const obj2 = {b:3, c:4};
const obj3 = {...obj1, ...obj2};
console.log(obj3); // {a:1, b:3, c:4}
function sum(a,b,c) {
return a+b+c;
}
const numbers = [1,2,3];
console.log(sum(...numbers)); // 6
剩餘參數跟展開有點像,能用在函式參數,把多個參數收起來
範例:
function sumAll(...nums){
return nums.reduce((acc,n)=>acc+n,0);
}
console.log(sumAll(1,2,3,4)); //10
小練習
1.從一個物件 {title:'JS',level:'Beginner',author:'Me'} 解構出 title 和 author
2.合併兩個陣列 [1,2] 和 [3,4,5]
3.寫一個函式 maxAll(...nums) 取出任意多數字的最大值
const course = {title:'JS',level:'Beginner',author:'Me'};
const {title,author} = course;
const arr = [...[1,2],...[3,4,5]];
function maxAll(...nums){
return Math.max(...nums);
}
整理一下:解構賦值能讓你從陣列、物件直接拆出需要的值,展開運算子能攤開陣列或物件,讓複製或合併資料更方便,而在函式參數裡當「剩餘參數」用,可以收集不固定數量的參數。