我正在使用 Object.assign()
将值复制到对象:
const { one, two, three } = attributes;
return Object.assign( props, {
"data-one": one,
"data-two": two,
"data-three": three
} );
如果属性的值为空,则返回 undefined。我希望它返回一个空字符串,或者最好不要复制任何空属性。
我试过这个:
const { one, two, three } = attributes;
var oneValue = one ? one : "";
var twoValue = two ? two : "";
var threeValue = three ? three : "";
return Object.assign( props, {
"data-one": oneValue,
"data-two": twoValue,
"data-three": threeValue
} );
它通过发送空值而不是 undefined 来工作,但看起来不是很花哨。有更好的方法来处理这个问题吗?
最佳答案
您可以在使用解构时定义默认值。
const attributes = { one: 'one' };
const { one = '', two = '', three = '' } = attributes;
const props = {}
console.log(Object.assign( props, {
"data-one": one,
"data-two": two,
"data-three": three
}));
最后,如果你有很多共同的行为,你可以只命名你想要复制的属性并编写一个循环。
关于javascript - JS 将未定义值转为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446685/