9.1 Spread (解构赋值)
JavaScript中的rest和spread操作为处理数组、对象和函数提供了广泛的可能性。 这些操作有助于简化代码,使其更加简洁和灵活。本节课我们将详细了解 rest 和 spread 的基本概念,以及它们的使用示例。
spread (...) 操作符允许在需要零个或多个元素的地方“解包”数组和对象。 这在复制、合并数组或对象以及将参数传递给函数时非常有用。
示例 1: 数组复制
在这个例子中,copiedArray 是 originalArray 的一个副本。
这里 … 操作符将数组解包成变量列表,[] 操作符将一组变量打包成一个新数组:
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray); // 输出: [1, 2, 3]
示例 2: 数组合并
在这个例子中,两个数组 array1 和 array2 被合并成一个新数组 combinedArray。
这里 … 操作符将两个数组解包成变量列表,而 [] 操作符将一组变量打包成一个新数组:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];
console.log(combinedArray); // 输出: [1, 2, 3, 4, 5, 6]
示例 3: 向函数传递参数
在这个例子中,数组 numbers 被解包为三个参数传递给函数 sum():
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 输出: 6
示例 4: 对象复制
在这个例子中,copiedObject 是 originalObject 的一个副本:
const originalObject = { a: 1, b: 2 };
const copiedObject = { ...originalObject };
console.log(copiedObject); // 输出: { a: 1, b: 2 }
示例 5: 对象合并
在这个例子中,两个对象 obj1 和 obj2 被合并成一个新对象 combinedObject:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObject = { ...obj1, ...obj2 };
console.log(combinedObject); // 输出: { a: 1, b: 2, c: 3, d: 4 }
9.2 Rest (剩余参数)
rest (...) 操作符允许将多个元素 聚合到一个数组中。 这在处理接收可变数量参数的函数时特别有用,也在解构赋值数组和对象时使用。
示例 1: 函数中的剩余参数
在这个例子中,函数 sum() 接收任意数量的参数并对其求和:
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // 输出: 6
console.log(sum(4, 5, 6, 7)); // 输出: 22
示例 2: 使用 rest 解构数组
在这个例子中,数组的前两个元素被赋给变量 first 和 second, 其余元素被收集到数组 rest 中:
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 输出: 1
console.log(second); // 输出: 2
console.log(rest); // 输出: [3, 4, 5]
示例 3: 使用 rest 解构对象
在这个例子中,属性 a 和 b 被提取到单独的变量中,而其余属性 被收集到对象 rest 中:
const { a, b, ...rest } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a); // 输出: 1
console.log(b); // 输出: 2
console.log(rest); // 输出: { c: 3, d: 4 }
9.3 rest 和 spread 在实际任务中的应用
示例 1: 按条件合并数组
在这个例子中,用户设置 userSettings 覆盖默认值 defaultSettings:
const defaultSettings = { theme: 'dark', showNotifications: true };
const userSettings = { showNotifications: false, fontSize: 14 };
const settings = { ...defaultSettings, ...userSettings };
console.log(settings); // 输出: { theme: 'dark', showNotifications: false, fontSize: 14 }
示例 2: 拆分数组
在这个例子中,数组 numbers 在提取出前两个元素后,被拆分为两部分:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const [first, second, ...rest] = numbers;
const firstHalf = rest.slice(0, Math.floor(rest.length / 2));
const secondHalf = rest.slice(Math.floor(rest.length / 2));
console.log(firstHalf); // 输出: [3, 4, 5, 6]
console.log(secondHalf); // 输出: [7, 8, 9, 10]
GO TO FULL VERSION