访问 javascript 函数参数的替代语法
Alternative syntax to access javascript function arguments
(function(arguments = {})
{
console.log(arguments)
}
)("a","b","c")
打印
$ node args.js
a
$ node --version
v8.9.4
在那种情况下有没有办法访问实际参数?
我建议不要覆盖 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 语法,则必须展开参数,因为 arguments
不存在于箭头(lambda 或匿名)函数中。
((...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)
(function(arguments = {})
{
console.log(arguments)
}
)("a","b","c")
打印
$ node args.js
a
$ node --version
v8.9.4
在那种情况下有没有办法访问实际参数?
我建议不要覆盖 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 语法,则必须展开参数,因为 arguments
不存在于箭头(lambda 或匿名)函数中。
((...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)