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

时间:2021-07-19 03:45:16

标签: javascript

在下面的代码中我不明白为什么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); 

3 个答案:

答案 0 :(得分:6)

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 所指的最近的封闭(非箭头)argumentsfoo 函数,所有参数都收集到一个类似数组的对象中并放入一个 { {1}} 标识符。上面的代码片段类似于:

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 的调用是 foofoo(3)theArgs,所以 [3] 包含 theArgs[0]

答案 1 :(得分:2)

arguments 是 Javascript 中的一个特殊关键字。 arguments 是一个类似数组的对象,可在 非箭头 函数内访问,其中包含传递给该函数的 arguments 的值。

它仅在该功能的范围内具有不同的含义。

即使不传递任何参数,对象存在

let arguments = [0,1,2,3];
function func1() {
  console.log(arguments);
  console.log(arguments[0]);
}

//Arrow functions do not have special arguments object
let func2 = () =>{
  console.log(arguments);
  console.log(arguments[0]);
}

func1(1, 2, 3);
func2(1,2,3);

箭头函数没有自己的 arguments 对象。因此,这里提到 arguments 时,您指的是在其外部定义的 arguments

答案 2 :(得分:2)

那是因为方法中的 argument 是您的方法参数。只需更改名称:

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

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