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
foo(1) `arguments[0]=1` right.?
And when we alert(b)
it should display 2 because we set 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.
FYI, in strict mode, none of the items on the arguments
object are aliased back to the named function arguments. But, in non-strict mode, the arguments that originally existed (and only those) are aliased back through the arguments
object.
Keep in mind that the arguments object is not a real Array. 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.
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. Not even .length
will update.
function foo(a, b){
arguments[1] = 2;
console.log(arguments.length); //1
}
foo(1);
Summary: Don't add elements to arguments
. Remember, arguments
is not an Array.
It makes sense that b
remains undefined
. When you run foo(1)
, it initializes a
to 1
and b
to undefined
. Modifying the arguments
object won't change that. That is, b
is not bound to arguments[1]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.