Javascript:使用一个变量,或者如果它是未定义的,则使用默认字符串 [英] Javascript: use either a variable, or if it's undefined, a default string

查看:114
本文介绍了Javascript:使用一个变量,或者如果它是未定义的,则使用默认字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var phrase = function(variable,defaultPhrase){
if(typeof variable ===undefined){
return defaultPhrase;
}
else {
返回变量;


$ / code>

这就是这样调用的:

  Ext.Msg.show({title:phrase(js_shutdown,'Shutdown'),// ... 

我想要做的是在变量未定义时使用默认短语,但是当我将未定义的变量传递给<$ c $如何解决这个问题?任何其他想法做到这一点?

解决方法

您不需要函数,通常使用 || 运算符:

  Ext.Msg.show({title:js_shutdown ||'Shutdown',// ... 

您可以看到 || 为:

  someValue || defaultValue 

对于字符串, defaultValue someValue ===



,则使用code>所有,你需要内嵌 typeof x ===undefined检查,因为你不能将该变量传递给一个函数(这是一个 ReferenceError )。


I have this code:

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

It's called like this:

Ext.Msg.show({title: phrase(js_shutdown,'Shutdown'), //...

What I want to do is to use a default phrase when the variable is not defined, but when I pass an undefined variable to phrase(), JS throws an undefined variable error. How do I fix this? Any other ideas to do this?

解决方案

You don't need a function. The || operator is usually used:

Ext.Msg.show({ title: js_shutdown || 'Shutdown', //...

You can see || as:

someValue || defaultValue

For strings, defaultValue is used if someValue === "".

If the variable is not defined at all, you'll need to inline the typeof x === "undefined" check, because you cannot pass the variable to a function (that's a ReferenceError).

这篇关于Javascript:使用一个变量,或者如果它是未定义的,则使用默认字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆