[removed] use either a variable, or if it's undefined, a default string

后端 未结 7 955
太阳男子
太阳男子 2020-12-10 00:49

I have this code:

var phrase = function (variable, defaultPhrase) {
    if (typeof variable === \"undefined\") {
        return defaultPhrase;
    }
    else         


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 01:36

    Usually using || is enough, like others have suggested. However, if you want to have 0, false and null as acceptable values, then you indeed need to check if the type of the variable is undefined. You can use the ternary operator to make it a one-liner:

    var variable;
    var defaultPhrase = "Default";
    var phrase = (typeof variable === "undefined" ? defaultPhrase : variable);
    console.log(phrase);
    // => "Default"
    

提交回复
热议问题