blu*_*yke 0 javascript indexing object ecmascript-6
我知道使用 ES6 JavaScript 对象,您可以使用 动态地将变量声明为对象键[]
,例如:
{[2 + 2]: "four!"}
给出输出{"4": "four!"}
问题是,是否可以使用类似的方法来通过变量等内联添加整个属性?意思是,假设我有以下测试对象:
var myObj = {
someProp: 2,
someOtherProp: 3 //only add this prop if a condition is met
}
Run Code Online (Sandbox Code Playgroud)
我可以在 for 的内联对象中编写什么内容someOtherProp
,以便仅在满足特定条件时将其添加到对象中吗?例如(伪代码),像这样
var myObj = {
someProp: 2,
[someBool ? null : "someOtherProp: 3"] //only add this prop if a condition is met
}
Run Code Online (Sandbox Code Playgroud)
会给出输出(考虑 someBool 为 true),如上面所示,但如果someBool
为 false,它会给我
var myObj = {
someProp: 2
}
Run Code Online (Sandbox Code Playgroud)
??
我知道我可以稍后使用 [] 索引器向对象添加属性(或删除属性),例如
someBool && (myObj["someOtherProp"] = 3)
Run Code Online (Sandbox Code Playgroud)
以及为此创建某种辅助函数,
但我想知道是否有办法使用内联对象表示法来做到这一点?
您可以使用条件运算符来传播对象。
{}
是一个中性值。
var myObj = {
someProp: 2,
...(someBool ? {} : { someOtherProp: 3 })
}
Run Code Online (Sandbox Code Playgroud)