How to pass the value 'undefined' to a function with multiple parameters?

前端 未结 12 2155
滥情空心
滥情空心 2020-12-14 14:26

I want to pass the value of \'undefined\' on a multiple parameter function but without omitting the parameter.

What do I mean with \"without omitting the paramet

相关标签:
12条回答
  • 2020-12-14 14:45

    You can use apply and an array of parameters to pass "undefined" as one of the parameters. For example, you wanted to pass parm1 as "undefined":

    function myFunction (parm1, parm2) {
    
        if(typeof (parm1) === "undefined"){
            alert("parm1 is undefined")
        }
    
        if(typeof (parm2) === "undefined"){
            alert("parm2 is undefined")
        }
    
    }
    
    var myParameters = [undefined, "abc"];
    
    myFunction.apply(valueForThis, myParameters );
    
    0 讨论(0)
  • 2020-12-14 14:46

    myFunction(undefined,"abc"); this way should work, what is the problem?

    see here

    Here is undefined documentation from mozilla, supported by all browsers

    0 讨论(0)
  • 2020-12-14 14:46

    Try to use this method if you plan on adding an indefinite amount of parameters:

    function myFunc(params) {
        // Define default values
        var name = 'John';
        var age = '40';
        // You can loop through them
        for (var p in params) {
            alert(p + ':' + params[p]);
        }
        // And read them in like this
        if (typeof params.name != 'undefined') {
            name = params.name;
        }
        if (typeof params.age != 'undefined') {
            age = params.age;
        }
        alert(name + ' ' + age);
    }
    
    alert('test1');
    myFunc({name:'Bob', age:'30'});
    alert('test2');
    myFunc({name:'Bob'});
    
    0 讨论(0)
  • 2020-12-14 14:47

    You need to handle the function call with undefined variable in the function code itself in one of the following way :-

     function myFunction (parm1, parm2) {
    
             if (parm1 !== undefined) {
                 // execute code if 1st param is undefined
            }
    
             if (parm2 !== undefined) {
                 // execute code if 2 param is undefined
            }
    
            // execute other part of code
    
        }
    

    Now you can call the above function in following ways:-

    myFunction(undefined,"abc"); // with 1st param value not known
    
    myFunction("cde",undefined); // with 2nd param value not known
    
    myFunction("cde","abc");  // with both param value known
    
    0 讨论(0)
  • 2020-12-14 14:56

    A better approach might be passing Object with named attributes and then look for those specific attribute values. This way you don't have to be dependent on number of arguments.
    Example: Object.dummy

    0 讨论(0)
  • 2020-12-14 15:00

    I just had an idea and it seems to work:

    var undf;
    
    myFunction(undf, "abc");
    

    I am sure there are better ways, however I post this

    0 讨论(0)
提交回复
热议问题