在Math类中,我们学习了如何定义新的运算符.例如:
(?, ?), x ? y = x + 2y这定义了?法律.对于任何实数x和y,x∘y是x + 2y.
示例:2 ? 2 = 2 + 4 = 6.
可以在JavaScript中定义这样的运算符吗?我知道一个函数可以完成这项工作:
function foo (x, y) { return x + 2 * y; }
Run Code Online (Sandbox Code Playgroud)
但是我希望有以下语法:
var y = 2 ? 2; // returns 6
Run Code Online (Sandbox Code Playgroud)
而不是这个:
var y = foo(2, 2);
Run Code Online (Sandbox Code Playgroud)
哪个是最接近这个问题的解决方案?