你好,我是沐爸,欢迎点赞、收藏、评论和关注。
扩展运算符有哪些使用场景?直接进入正题
一、复制数组
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;
二、合并数组
const part1 = [1, 2, 3];
const part2 = [4, 5, 6];
const all = [...part1, ...part2];
console.log(all); // 输出: [1, 2, 3, 4, 5, 6]
三、数组去重
const numbers = [1, 2, 2, 3, 3, 4, 5, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // 输出: [1, 2, 3, 4, 5]
四、函数参数数量不固定
function sum(...numbers) {
return numbers.reduce((total, current) => total + current, 0);
}
console.log(sum(1, 2, 3, 4, 5));