且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Javascript中,如何有条件地将成员添加到对象?

更新时间:2023-11-12 17:52:52

在纯粹的Javascript中,我想不出任何更具风格的东西比你的第一个代码片段。

In pure Javascript, I cannot think of anything more idiomatic than your first code snippet.

然而,如果使用jQuery库并不是不可能的话,那么 $ .extend()应该符合您的要求,因为文档说:

If, however, using the jQuery library is not out of the question, then $.extend() should meet your requirements because, as the documentation says:


未复制未定义的属性。

Undefined properties are not copied.

因此,您可以写:

var a = $.extend({}, {
    b: conditionB ? 5 : undefined,
    c: conditionC ? 5 : undefined,
    // and so on...
});

并获得您期望的结果(如果 conditionB false ,然后 b 将不存在于 a 中)。

And obtain the results you expect (if conditionB is false, then b will not exist in a).