擴展運算符
擴展運算符是一個與剩余參數(shù)作用相反的過程,剩余參數(shù)是把很多參數(shù)整合成一個數(shù)組鸯两,擴展運算符是把一個可遍歷對象的每個元素擴展為一個新的參數(shù)序列
// 合并兩個數(shù)組
const youngers = ['George', 'John', 'Thomas'];
const olders = ['James', 'Adrew', 'Martin'];
let members = [...youngers,...olders];
// 分割字符串
let str = 'laravel';
const arr = [...str];
str = arr.map(char => `<span class="red">${char}</span>`).join('');
console.log(str);
運用場景
- 替換
Array.from()
把類數(shù)組的nodelist對象轉(zhuǎn)換為數(shù)組
const todos = [...document.querySelectorAll('li')];
- 擴展對象的屬性
const favourites = {
color: ['yellow', 'red'],
fruits: ['apple', 'mongo']
}
const shoppingList = ['milk', 'sweets', ...favourites.fruits];
- 對數(shù)組進行刪除
const todos = [
{ id: 3, name: 'go to shop', completed: false },
{ id: 5, name: 'watch tv', completed: true },
{ id: 6, name: 'coding', completed: false }
];
const id = 5;
const index = todos.findIndex(todo => todo.id === id);
const arr = [...todos.slice(0, index), ...todos.slice(index + 1)];
- 在函數(shù)中的應(yīng)用
const fruit = ['apple', 'banana', 'pear'];
const newFruit = ['orange', 'mongo'];
fruit.push(...newFruit);
console.log(fruit);
const dateFields = [2017,6,8];
const date = new Date(...dateFields);
console.log(date);