How best to determine if an argument is not sent to the JavaScript function

后端 未结 13 721
猫巷女王i
猫巷女王i 2020-11-28 00:40

I have now seen 2 methods for determining if an argument has been passed to a JavaScript function. I\'m wondering if one method is better than the other or if one is just ba

13条回答
  •  无人及你
    2020-11-28 01:18

    It can be convenient to approach argument detection by evoking your function with an Object of optional properties:

    function foo(options) {
        var config = { // defaults
            list: 'string value',
            of: [a, b, c],
            optional: {x: y},
            objects: function(param){
               // do stuff here
            }
        }; 
        if(options !== undefined){
            for (i in config) {
                if (config.hasOwnProperty(i)){
                    if (options[i] !== undefined) { config[i] = options[i]; }
                }
            }
        }
    }
    

提交回复
热议问题