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

后端 未结 7 930
太阳男子
太阳男子 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"
    
    0 讨论(0)
提交回复
热议问题