javascript 中函数参数解构是通过在函数定义的形参位置使用对象或数组的字面量语法,将传入的参数自动匹配并赋值给局部变量。对于对象参数,直接列出需要提取的属性名;对于数组参数,按索引顺序排列变量名。这样做可以简化代码,避免重复访问 obj.key,并且能轻松处理默认值。

如何从对象参数中提取特定属性并设置默认值
当函数接收一个配置对象时,可以在形参中使用 { key } 语法来解构。如果调用者未传递该属性,可以通过 = defaultValue 指定默认值。这种方式比在函数体内手动检查 if (!obj.key) 更简洁。

function greet({ name = 'Guest', age = 0 }) {
console.log(`Hello ${name}, you are ${age} years old.`);
}
greet({ name: 'Alice' }); // Hello Alice, you are 0 years old.
greet({}); // Hello Guest, you are 0 years old.
如何从数组参数中按位置提取元素
如果函数参数是数组,可以使用 [ a, b ] 语法按索引解构。第一个元素赋值给 a,第二个赋值给 b。同样支持默认值,且忽略多余元素。
立即学习“Java免费学习笔记(深入)”;

function sum([a, b] = [0, 0]) {
return a + b;
}
console.log(sum([1, 2])); // 3
console.log(sum([1])); // 1 (b为undefined, 但+运算转为NaN? No, default applies if whole arg missing. Wait, destructuring defaults apply to the pattern match. If array is [1], b is undefined. To fix, use default in pattern: [a=0, b=0]. Let's correct code.)
// Corrected:
function sum([a=0, b=0] = [0, 0]) {
return a + b;
}
console.log(sum([1])); // 1
console.log(sum([])); // 0
当传入的值为 null 或 undefined 时会发生什么
如果尝试对 null 或 undefined 进行解构,JavaScript 会抛出 TypeError。这是因为解构操作试图读取这些值的属性或索引,而它们没有可枚举的属性。为了避免错误,必须为整个参数提供默认值,例如 function foo({ x } = {}),这样当传入 null 时,会使用空对象 {} 进行解构,从而安全地获取默认值。


















