技術浮浪貢

JavaScript 有條件增加物件屬性的簡短寫法

The shortest way to conditional insert properties into an object literal 看到的。

例如,為了避免出現 undefined 的 property ,通常會這樣寫:

1const obj = {};  
2if (input1) {  
3    obj.prop1 = input1;  
4}  
5if (input2) {  
6    obj.prop2 = input2;  
7}

可以寫成:

1const obj = {  
2    ...input1 && { prop1: input1 },  
3    ...input2 && { prop2: input2 }, 
4};

#JavaScript

« 上一篇

下一篇 »

相關文章