将arguments对象分配给变量

时间:2021-03-26 23:15:11

So, I'm quite new to Javascript and was wondering about the arguments object (as probably anyone does who is new to the language) using NodeJS.

所以,我对Javascript很陌生,并且想知道使用NodeJS的参数对象(可能是对语言不熟悉的人)。

Consider this snippet which simply implements printf style formatting

考虑一下这个简单实现printf样式格式的片段

function format(formatString) {
  var i = 1;
  return formatString.replace(regex, function(match) {
    switch(match) {
      case "%s": return arguments[i++];
    }
  });
}

Calling the function format("Hi my name is %s. Im %s years old", "Jon", "30") results in following output My name is 11. Im My name is %s. Im %s years old years old.

调用函数格式(“我的名字是%s。我%s岁”,“Jon”,“30”)导致以下输出我的名字是11.我的名字是%s。我%s岁。

Researching about arguments showed that we are not dealing with a "real" array here and that using Array.slice(arguments) actually produces one. However, I'm struggling with following fact:

研究参数表明我们在这里没有处理“真正的”数组,并且使用Array.slice(arguments)实际上产生了一个。但是,我正在努力遵循以下事实:

Performing this simple assignment var args = arguments and than referencing args instead of arguments lets my code work perfectly (I stumbled across this inspecting the NodeJS source for util.format)

执行这个简单的赋值var args = arguments而不是引用args而不是参数让我的代码完美地工作(我偶然发现了这个检查用于util.format的NodeJS源代码)

My Question is now, what kind of black magic is V8 practicing here? Is there any conversion performed in the background? And if, what kind of conversion? Node tells me that both variable are of type object.

我的问题是现在,V8在这里练习什么样的黑魔法?是否在后台执行了任何转换?如果,转换是什么样的? Node告诉我两个变量都是object类型。

Thanks in advance for helping me out.

在此先感谢帮助我。

1 个解决方案

#1


This will not work. arguments only means anything inside the function it is in. In your case, arguments is referencing the arguments of the anonymous function. You need to capture the arguments in the parent scope. Something like:

这不行。参数只表示它所在函数内部的任何内容。在您的情况下,参数引用匿名函数的参数。您需要捕获父作用域中的参数。就像是:

function format(formatString) {
  var i = 1, args = Array.prototype.slice.call(arguments);
  return formatString.replace(/%[a-z]/gi, function(match) {
    switch(match) {
      case "%s": return args[i++];
    }
  });
}
format("Hi my name is %s. Im %s years old", "Jon", "30");

// Output: "Hi my name is Jon. Im 30 years old"

#1


This will not work. arguments only means anything inside the function it is in. In your case, arguments is referencing the arguments of the anonymous function. You need to capture the arguments in the parent scope. Something like:

这不行。参数只表示它所在函数内部的任何内容。在您的情况下,参数引用匿名函数的参数。您需要捕获父作用域中的参数。就像是:

function format(formatString) {
  var i = 1, args = Array.prototype.slice.call(arguments);
  return formatString.replace(/%[a-z]/gi, function(match) {
    switch(match) {
      case "%s": return args[i++];
    }
  });
}
format("Hi my name is %s. Im %s years old", "Jon", "30");

// Output: "Hi my name is Jon. Im 30 years old"