【发布时间】:2021-05-14 13:06:08
【问题描述】:
(function(arguments = {})
{
console.log(arguments)
}
)("a","b","c")
打印
$ node args.js
a
$ node --version
v8.9.4
在这种情况下有没有办法访问实际参数?
【问题讨论】:
标签: javascript arguments
(function(arguments = {})
{
console.log(arguments)
}
)("a","b","c")
打印
$ node args.js
a
$ node --version
v8.9.4
在这种情况下有没有办法访问实际参数?
【问题讨论】:
标签: javascript arguments
我建议不要在 function 定义中覆盖内置的 arguments 变量。
您可以使用 ...vargs 来传播预期的参数。
(function(...vargs) {
console.log(arguments); // Built-in arguments
console.log(vargs); // Variable (spread) arguments
})("a", "b", "c");
.as-console-wrapper { top: 0; max-height: 100% !important; }
请查看 MDN 上的 the arguments object 了解更多信息。
文档指出,如果您使用 ES6 语法,则必须分散参数,因为箭头(lambda 或匿名)函数内部不存在 arguments。
((...vargs) => {
try {
console.log(arguments); // Not accessible
} catch(e) {
console.log(e); // Expected to fail...
}
console.log(vargs); // Variable (spread) arguments
})("a", "b", "c");
.as-console-wrapper { top: 0; max-height: 100% !important; }
【讨论】:
function f1() { console.log(Array.from(arguments)) }
f1(1, 2, 3)
function f2(...args) { console.log(args) }
f2(4, 5, 6)
【讨论】: