JavaScript 中解构赋值怎么设置默认值
在 javascript 中,解构赋值的默认值通过等号 = 指定。当右侧对象或数组对应位置的属性值为 undefined 时,左侧变量将使用默认值;若该位置存在任何非 undefined 的值(包括 null、false 或空字符串),则不会触发默认值逻辑。

对象解构的默认值行为
对于对象解构,如果目标键不存在于源对象中,或者其值为 undefined,则使用默认值。以下代码展示了这一行为:

const config = { theme: 'dark' };
// 1. 存在且非 undefined:使用实际值
const { theme } = config; // theme = 'dark'
// 2. 键不存在:使用默认值
const { language = 'en' } = config; // language = 'en'
// 3. 值为 null:不使用默认值
const { version = '1.0' } = { version: null };
console.log(version); // 输出: null
// 4. 值为 false:不使用默认值
const { active = true } = { active: false };
console.log(active); // 输出: false数组解构的默认值行为
数组解构同样遵循 undefined 检查原则。如果数组索引越界或对应元素为 undefined,则应用默认值:
立即学习“Java免费学习笔记(深入)”;

const arr = [1, 2]; // 1. 索引存在:使用实际值 const [a] = arr; // a = 1 // 2. 索引越界:使用默认值 const [, , c = 3] = arr; // c = 3 // 3. 值为 undefined:使用默认值 const [d = 4] = [undefined]; // d = 4 // 4. 值为 null:不使用默认值 const [e = 5] = [null]; // e = null
基于默认值表达式的计算问题
默认值不仅可以是字面量,还可以是表达式或函数调用。当需要延迟计算或依赖其他变量时,这种特性非常有用。例如,在解构时调用一个函数作为默认值,只有当对应属性为 undefined 时才会执行该函数:
function getDefaultName() {
console.log('Calculating default name...');
return 'Guest';
}
const user1 = { name: 'Alice' };
const { name = getDefaultName() } = user1;
// 控制台不输出,name = 'Alice'
const user2 = {};
const { name = getDefaultName() } = user2;
// 控制台输出: Calculating default name...
// name = 'Guest'


















