[英]Can I conditionally pass a property into an object?
是否可以有条件地将属性传递给基于对象的 function:
myFunction
.x()
.y()
.x();
在这里,我只想根据条件传入y()
,例如:
myFunction
.x()
[isTrue && y()]
.x();
非常感谢任何帮助,谢谢
如果您想动态地在不同的方法之间进行选择,您可以使用该语法。 但是当条件为假时,没有可以替代y
的“什么都不做”方法。
请改用if
语句。
let temp = myFunction.x();
if (isTrue) {
temp = temp.y();
}
temp.x()
这是另一个更像您最初想象的解决方案。 Barmar 的解决方案可以正常工作,但我想我会展示一种更像您想象的不同方法:
obj
.x()
[doIt ? "y" : "noop"]()
.x();
在此方案中, doIt
是任何 boolean 或 boolean 表达式, .noop()
是 object 上的“无操作”方法。
而且,这是一个可以在片段中运行的工作示例:
const obj = { x() { console.log("executing x() method"); return this; }, y() { console.log("executing y() method"); return this; }, noop() { console.log("executing noop() method"); return this; } } // try both values of the boolean for (let doIt of [true, false]) { console.log(`\nresults for doIt = ${doIt}`); obj.x() [doIt? "y": "noop"]().x(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.