简体   繁体   English

参数对象未显示正确的结果

[英]Arguments object is not showing correct result

look at this code 看这段代码

enter code here
function foo(a, b) {
    arguments[1] = 2;
    alert(b);
}

console.log(foo(1));

Its showing undefined I am not able to understand why.. because when we pass arguents 其显示undefined我无法理解为什么..因为当我们通过辩论者时

foo(1) `arguments[0]=1` right.?

And when we alert(b) it should display 2 because we set arguments[1] = 2 ; 并且当我们alert(b)它应该显示2,因为我们设置了arguments[1] = 2 I am confused.. please help. 我很困惑..请帮助。 Thanks. 谢谢。

Only the original arguments that existed when the function was called are "aliased" through the arguments object such that you could change the arguments object and have it automatically affect the named function argument also. 通过arguments对象仅对调用函数时存在的原始参数进行“别名”处理,以便您可以更改参数对象并使其自动影响命名的函数参数。

FYI, in strict mode, none of the items on the arguments object are aliased back to the named function arguments. 仅供参考,在严格模式下, arguments对象上的所有项目都不会别名化回命名的函数形参。 But, in non-strict mode, the arguments that originally existed (and only those) are aliased back through the arguments object. 但是,在非严格模式下,原来存在的参数(只有那些参数)会通过arguments对象作为别名。

Keep in mind that the arguments object is not a real Array. 请记住,arguments对象不是真正的数组。 It is a special type of object and this special "aliasing" behavior only exists for the properties of that object that were originally placed there when the function was called, not for properties that you might have added yourself. 它是对象的一种特殊类型,这种特殊的“混叠”行为仅存在于调用函数时最初放置在该对象中的对象的属性,而不存在于您可能自己添加的属性。 Since arguments[1] did not originally exist, it does not have this special feature. 由于arguments[1]最初不存在,因此没有此特殊功能。

See this: 看到这个:

function foo(a, b) {
    console.log(arguments.length);    // 1
    arguments[1] = 2;
    console.log(arguments.length);    // still 1
    console.log(arguments[1]);        // does show 2
    console.log(b);                   // undefined, arguments[1] is not aliased to b
}

console.log(foo(1));

Manually adding elements into arguments will not set the setters and getters properly. 手动将元素添加到arguments将无法正确设置setter和getter。 Not even .length will update. 甚至.length都不会更新。

function foo(a, b){
    arguments[1] = 2;
    console.log(arguments.length);   //1
}

foo(1);

Summary: Don't add elements to arguments . 简介:不要将元素添加到arguments Remember, arguments is not an Array. 请记住, arguments不是数组。

It makes sense that b remains undefined . b保持undefined是有道理的。 When you run foo(1) , it initializes a to 1 and b to undefined . 运行foo(1) ,它将a初始化为1并将b初始化为undefined Modifying the arguments object won't change that. 修改arguments对象不会改变它。 That is, b is not bound to arguments[1] . 也就是说, b没有绑定arguments[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM