我写了一个广泛使用默认参数的 javascript 项目,例如:
function hello(x = true){
...
}
现在我想从命令行调用我的代码。我尝试过使用 Rhino、Nashorn 和 Node,但它们在遇到默认参数时都会抛出错误。在 Rhino 中,错误是:
js: "resource.js", line 6: missing ) after formal parameters
js: function hello(x = true){
js: ..................^
js: "resource.js", line 1: Compilation produced 1 syntax errors.
有什么方法可以从命令行调用我的项目,而不必重写我的所有代码来摆脱默认参数?
谢谢
编辑:将 node.js 从版本 4 更新到版本 8 后,这有效。我将使用 node.js,但我仍然不知道这在 rhino 上是否可行。
最佳答案
你总是有办法复制默认参数的行为,但它不像新版本的 javascript 那样可读。
如果您只有一个参数,最直接的方法是在您的函数中检查undefined
,即:
js> function hello(x){
> if (x === undefined) x = 5;
> return x;
> }
js> hello()
5
js> hello(42)
42
另一方面,如果您的函数包含更多参数,我建议您使用一个对象作为输入,然后检查 undefined
值,如上所示:
js> function hello(args){
> if (args.x === undefined) args.x = 5;
> return args.x + "-" + args.y;
> }
js> hello({y: 12})
5-12
js> hello({x: 1, y: 42})
1-42
关于javascript - 从 Rhino 调用脚本时,有没有办法在 javascript 函数中包含可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46656646/