【问题标题】:JavaScript arguments object does not have all parametersJavaScript arguments 对象没有所有参数
【发布时间】: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);

问题

  1. 为什么这不起作用?
  2. 如果我有多个参数,如何访问函数?

【问题讨论】:

  • JSON 不能包含函数作为值,所以你最终会得到null。
  • 另请注意,arguments 对象在现代 JavaScript 中或多或少已被弃用。
  • console.log 不需要您 JSON.stringify 对象。它会以人类可读的方式为您将它们串起来
  • 添加到 Pointy 的评论中,扩展运算符现在是访问可变参数的公认方式。 (...myArgs) => console.log(...myArgs);
  • @Pointy 实际上,我认为 JSON.stringify(fn) 返回 undefined 但在容器的上下文中,它会转换为 null。

标签: javascript arguments


【解决方案1】:

默认情况下,JSON.stringify() 不序列化函数。

...但它可以。提供自定义的replacer 回调并自己处理函数的序列化:

var values = [1, false, {foo:2}, function bar() {}];

console.log(JSON.stringify(values, function(key, value) {
  if ("function" === typeof value) {
    return value.toString();
  }
  return value;
}));

见Function.prototype.@987654322@和JSON.@987654323@。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-18
    • 2012-01-09
    • 1970-01-01
    • 2019-02-10
    • 2012-09-23
    • 2023-04-05
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多