为什么foo函数内部和外部的参数值不同

在下面的代码中,我不明白为什么 arguments[0] 在 foo 函数中打印 3,这个问题的解决方案只是给出了提示:

您需要检查 DOM 中是否存在参数

显然参数在里面DOM。或者我错过了什么?

var arguments = [1, 2, 3];
var arr = () => arguments[2];
arr()
console.log(arr()); // understandable it prints 3
console.log(arguments[0]);// understandable it prints 1

function foo(n) {
console.log(arguments[0]); // do not understand why it prints 3
   var f = () => arguments[0] + n; 
   return f();
}
console.log(arguments[0]); // understandable it prints 1
foo(3); 

回答

arguments在某些情况下具有特殊含义:它指的是传递给最近祖先function参数。出于这个原因,最好不要定义命名的变量以arguments避免混淆。尝试一下:

const arr = [1, 2, 3];
const someFn = () => arr[2];
someFn()
console.log(someFn());
console.log(arr[0]);

function foo(n) {
  console.log(arr[0]);
  const f = () => arr[0] + n;
  return f();
}
foo(3);
console.log(arr[0]);

每个日志背后的原因应该很清楚,因为现在没有任何有趣的事情在进行。

原始代码的问题是,当您执行以下操作时:

function foo(n) {
  console.log(arguments[0]); // do not understand why it prints 3

最近的封闭(非箭头)function,该arguments指的是foo功能,并且所有参数被收集到一个数组状物体并放入arguments标识符。上面的代码片段类似于:

function foo(n) {
  const theArgs = [n]; // collect all arguments into an array-like object
  console.log(theArgs[0]); // do not understand why it prints 3

并且由于调用foowas foo(3)theArgsis [3],所以theArgs[0]contains 3


以上是为什么foo函数内部和外部的参数值不同的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>