javascript Javascript用if语句声明变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19505261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:48:56  来源:igfitidea点击:

Javascript declare variable with if statement

javascript

提问by Jamie Hutber

I've no doubt this is a duplication of a question, but I can't find the correct search terms.

我毫不怀疑这是一个问题的重复,但我找不到正确的搜索词。

I'd like a shorthand variable declaration that won't be defined if its false. I remember it looking something like this:

我想要一个速记变量声明,如果它是假的,就不会被定义。我记得它看起来像这样:

 var jamie = jamie : 'or maybe not';

If this makes it easier to understand, this is what I'm actually trying to achieve.

如果这样更容易理解,这就是我真正想要实现的目标。

    if($('body').hasClass('loggedin')){
        var loggedin = true;
    }

Remember, I have no idea what it is.

记住,我不知道它是什么。

回答by TGH

 var jamie = someVarThatCanBeUndefined || 'or maybe not';

You can use the above to do coalescing

您可以使用上述内容进行合并

Here is an answer with more details Is there a "null coalescing" operator in JavaScript?

这是包含更多详细信息的答案 JavaScript 中是否有“空合并”运算符?

If you wanted short hand notation for if

如果你想要简写 if

Try this instead:

试试这个:

boolCondition ? "OneStringForTrue" : "AnotherForFalse"

This is often called the

这通常被称为

Conditional (Ternary) Operator (?:) (JavaScript)

回答by Robbie Wxyz

var jamie = jamie || 'or maybe not';

Simple as that.

就那么简单。

回答by I?ya Bursov

hasClass already boolean:

hasClass 已经是布尔值:

var loggedin = $('body').hasClass('loggedin');

回答by Tibos

First of all, the simplest way to initialize loggedIn is by simply assigning it the return value of hasClass, which is a boolean:

首先,初始化loggedIn的最简单方法是简单地为其分配hasClass的返回值,它是一个布尔值:

var loggedin = $('body').hasClass('loggedin');

What you remember is a short way to provide default value for variables, by using the logical OR operator which returns the first value which evaluates to true or the last value if all are false:

您所记得的是一种为变量提供默认值的简短方法,通过使用逻辑 OR 运算符,该运算符返回第一个值为真或最后一个值(如果全部为假):

jamie = jamie || 'or maybe not'; // identical to if (!jamie) jamie = 'or maybe not';

Finally, the || operator fails in certain edge cases where the initial value of the variable is falsy:

最后,|| 在变量的初始值为假的某些边缘情况下,运算符会失败:

function f(number) {
  number = number || 10; // if number is not provided, default to 10
  console.log(number);
}
f(0) // whoops, number was provided, but it will log 10 instead.

In such cases (usually happens when you want to check only against nulland undefined), not all falsy values, you can use the conditional operator:

在这种情况下(通常发生在您只想检查null和 时undefined),而不是所有假值,您可以使用条件运算符:

number = number != null ? number : 10;

It's slightly more verbose, but still quite an elegant way to provide defaults.

它稍微冗长一些,但仍然是一种提供默认值的优雅方式。