在JavaScript中设置对象的默认值可以通过多种方式实现,以下是几种常见的方法:
||
)const obj = {
name: 'John',
age: 30,
address: ''
};
const defaultValues = {
name: 'Unknown',
age: 0,
address: 'No address provided'
};
const filledObj = {
name: obj.name || defaultValues.name,
age: obj.age || defaultValues.age,
address: obj.address || defaultValues.address
};
console.log(filledObj);
// 输出: { name: 'John', age: 30, address: '' }
??
)const obj = {
name: 'John',
age: 30,
address: ''
};
const defaultValues = {
name: 'Unknown',
age: 0,
address: 'No address provided'
};
const filledObj = {
name: obj.name ?? defaultValues.name,
age: obj.age ?? defaultValues.age,
address: obj.address ?? defaultValues.address
};
console.log(filledObj);
// 输出: { name: 'John', age: 30, address: '' }
const obj = {
name: 'John',
age: 30,
address: ''
};
const defaultValues = {
name: 'Unknown',
age: 0,
address: 'No address provided'
};
function getDefaultValue(key) {
return obj[key] === undefined || obj[key] === null || obj[key] === '' ? defaultValues[key] : obj[key];
}
const filledObj = {
name: getDefaultValue('name'),
age: getDefaultValue('age'),
address: getDefaultValue('address')
};
console.log(filledObj);
// 输出: { name: 'John', age: 30, address: '' }
原因:可能是由于对象的属性已经被显式设置为undefined
或null
,或者使用了错误的默认值逻辑。
解决方法:
undefined
或null
。||
)或空值合并运算符(??
)来正确设置默认值。const obj = {
name: undefined, // 显式设置为undefined
age: 30,
address: ''
};
const filledObj = {
name: obj.name ?? 'Unknown', // 使用空值合并运算符
age: obj.age ?? 0,
address: obj.address ?? 'No address provided'
};
console.log(filledObj);
// 输出: { name: 'Unknown', age: 30, address: '' }
通过以上方法,可以有效地在JavaScript中设置对象的默认值,并确保代码的健壮性和可靠性。
领取专属 10元无门槛券
手把手带您无忧上云