简体   繁体   中英

What happens when I give more parameters than required in the function in Javascript?

Assume -

function noname(a, b) {
//code
}

and I give -

noname(4,5,6,7);

What will happen then?

The additional parameters will simply get ignored.

They will however be available as part of the arguments pseudo-array, eg as arguments[2] , arguments[3] .

If you give fewer variables than are required then the missing ones will be undefined .

As Alnitak said, they become undefined since they haven nothing binding them, unless as stated: arguments[i] is used`.

A good practice is to first test how many original parameters the function had stated by using the .length method available on all functions.

noname.length === 2 // in your case

This makes it easier to then save any additional arguments (just in case we might want to use them)

jsFiddle Demo

function noname (a, b) {
    console.log('Original parameters in this function: ' + noname.length);

    var additionalParameters = [];

    if (arguments.length > noname.length) {
        for (i = 0; i < arguments.length - noname.length; i++) {
            // We need to start arguments off at index: 2 in our case
            // The first 0 & 1 parameters are a, b

            additionalParameters[i] = arguments[i + noname.length];
            // These of course will be saved starting at 0 index on additionalParameters
        }
    }

    console.log(additionalParameters);
}

noname(1, 2, 3, 4, 5);

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.

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