我正在尝试执行以下操作以满足代码构建器(具体来说是 Sencha Cmd)的要求。
这就是我需要做的本质。关键因素是函数体必须以对象文字的返回结束。由于构建器中的限制,我无法返回变量。因此,如果参数“includeB”为真,如何在下面的伪代码点添加属性“b”,但如果参数为假,则根本不添加属性。即不允许 b==undefined 或 b==null。
也许这是不可能的。
function create(includeB) {
// Can have code here but the final thing MUST be a return of the literal.
// ...
return {
a : 1
// pseudo code:
// if (includeB==true) then create a property called b
// and assign a value of 2 to it.
// Must be done right here within this object literal
}
}
var obj = create(false);
// obj must have property 'a' ONLY
var obj = create(true);
// obj must have properties 'a' and 'b'
感谢阅读和考虑,
默里
最佳答案
如果可以使用 ES6,请使用 spread properties .
function create(includeB) {
return {
a : 1,
...(includeB ? { b: 2 } : {}),
};
}
关于javascript - 如何有条件地将属性添加到 javascript 对象文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568760/