【发布时间】:2017-06-21 14:19:38
【问题描述】:
背景
我正在学习 arguments 对象如何在函数中工作。我注意到理论上,这个对象会将所有参数传递给函数。
在实践中我得到了完全不同的结果。
代码
以下代码是一个测试函数,它会打印它接收到的参数:
function test(myArgs){
console.log(`myArgs: ${myArgs}`);
console.log(`arguments obj: ${JSON.stringify(arguments)}`);
console.log(`arguments array ${JSON.stringify(Array.from(arguments))}`);
}
第一行打印myArgs,另外两行以几种不同的方式打印arguments对象。
用一些简单的方法来执行函数:
test("hello", 56, 60, 5);
myArgs: hello
arguments obj: {"0":"hello","1":56,"2":60,"3":5}
arguments array ["hello",56,60,5]
问题
当我将函数作为参数之一传递时,问题就出现了,比如说,一个回调:
test("hello", () => console.log("HelloWorld"), 60, 5);
myArgs: hello
arguments obj: {"0":"hello","2":60,"3":5}
arguments array ["hello",null,60,5]
这真是出乎意料...
代码
以下是举例说明此行为的 sn-p:
function test(myArgs){
console.log(`myArgs: ${myArgs}`);
console.log(`arguments obj: ${JSON.stringify(arguments)}`);
console.log(`arguments array ${JSON.stringify(Array.from(arguments))}`);
}
test("hello", 56, 60, 5);
test("hello", () => console.log("HelloWorld"), 60, 5);
问题
- 为什么这不起作用?
- 如果我有多个参数,如何访问函数?
【问题讨论】:
-
JSON 不能包含函数作为值,所以你最终会得到
null。 -
另请注意,
arguments对象在现代 JavaScript 中或多或少已被弃用。 -
console.log 不需要您 JSON.stringify 对象。它会以人类可读的方式为您将它们串起来
-
添加到 Pointy 的评论中,扩展运算符现在是访问可变参数的公认方式。 (...myArgs) => console.log(...myArgs);
-
@Pointy 实际上,我认为
JSON.stringify(fn)返回undefined但在容器的上下文中,它会转换为null。
标签: javascript arguments