How to get value from Object, with default value

前端 未结 4 820
梦毁少年i
梦毁少年i 2021-02-01 00:13

I constantly find myself passing config values to functions accessing them like this:

var arg1 = \'test1\';
if(isUndefined(config.args.arg1)){
  arg1 = config.ar         


        
4条回答
  •  一个人的身影
    2021-02-01 01:00

    Generally, one can use the or operator to assign a default when some variable evaluates to falsy:

    var foo = couldBeUndefined || "some default";
    

    so:

    var arg1 = config.args.arg1 || "test";
    var arg2 = config.args.arg2 || "param2";
    

    assuming that config.args is always defined, as your example code implies.

提交回复
热议问题