扩展运算符
扩展运算符是一个与剩余参数作用相反的过程,剩余参数是把很多参数整合成一个数组,扩展运算符是把一个可遍历对象的每个元素扩展为一个新的参数序列
// 合并两个数组
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()
把类数组的nodelist对象转换为数组
const todos = [...document.querySelectorAll('li')];
- 扩展对象的属性
const favourites = {
color: ['yellow', 'red'],
fruits: ['apple', 'mongo']
}
const shoppingList = ['milk', 'sweets', ...favourites.fruits];
- 对数组进行删除
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)];
- 在函数中的应用
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);