clumsyfingers
clumsyfingers

Reputation: 520

How to push a new argument to javascript's arguments object

Got a weird case where the javascript arguments object is being heavily relied on. I've got the problem 'solved' but was wondering if someone could explain to me some of the behavior that results from this code:

function whatweget(arg1,arg2,arg3) {
    while(arguments.length<3) { arguments[arguments.length++] = undefined; }
    console.log(arguments);
}
function argstest() {
    arguments[arguments.length++] = 3;
    console.log(arguments);
}
whatweget(1,2);
whatweget(1,2,3);
whatweget(1,2,3,4);
argstest(3);

Outputs in Chrome:

[1, 2, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
[1, 2, 3]
[1, 2, 3, 4]
[3, 3]

Inspecting the arguments object at the whatweget console.log shows it having 20 items, the first 3 are bolded while the last 17 are slightly faded. Inspecting arguments in the argstest console.log these 'ghost' parameters don't show up. This is not a problem as subsequent scripts will be passed 'arguments' and use the 'length' parameter which is set properly, but was wondering if anyone had any insight into this behavior?

Oh, and btw, Firefox 8 is totally cool with this behavior. It does everything as expected, well, except that it doesn't show the arguments object in the Watch inspector, though it will show it as an array when you hover your mouse over it. Bad Firefox, bad bad firefox.

Upvotes: 2

Views: 5046

Answers (1)

shredder
shredder

Reputation: 401

If you are testing in the developer console, I think it is a console display bug.

If you do a for-in over the arguments object in order to enumerate all of its properties, you only get the 3 you would expect.

function whatweget(arg1,arg2,arg3) {
    while(arguments.length<3) { arguments[arguments.length++] = undefined; }
    for( var n in arguments ) console.log(n, arguments[n]);
}

0 1
1 2
2 undefined

Or if I return the arguments object, and test for properties using in, it shows the properties are not there.

function whatweget(arg1,arg2,arg3) {
    while(arguments.length<3) { arguments[arguments.length++] = undefined; }
    return arguments;
}

var args = whatweget(1,2);

console.log( '2' in args );  is true
console.log( '5' in args );  is false

Upvotes: 1

Related Questions