简体   繁体   English

使用|| 在javascript中执行null / undefined检查?

[英]Using || to perform null / undefined check in javascript?

I've read code that has snippets similar to this but I obviously forgot the semantics: 我读过的代码片段与此类似,但是我显然忘记了语义:

        let serve = target || "Hello World";

In other words if target is null , the serve equals Hello World . 换句话说,如果target为null ,则发球等于Hello World My goal, since target is null, is to get serve to be Hello Word ... 由于目标为null,因此我的目标是成为“ Hello Word

If I run the function as stated node prints this: 如果我按所述方式运行该函数,则将输出以下内容:

ReferenceError: target is not defined

You need to define the variable target first. 您需要先定义变量target Here are some examples: 这里有些例子:

 let target; let serve = target || "Hello World"; console.log(serve); // prints "Hello World"; target = null; serve = target || "Hello World"; console.log(serve); // still prints "Hello World"; target = "Cat"; serve = target || "Hello World"; console.log(serve); // prints "Cat" 

Using a || b 使用a || b a || b will return b if a is falsy. 如果a为假,则a || b将返回b The falsy values from You Don't Know JS: Types and Grammar - Chapter 4: Coercion are: 您不知道JS:类型和语法-第4章:强制》中的虚假值是:

  • undefined
  • null
  • false
  • +0 , -0 , and NaN +0-0NaN
  • ""

If you'd like to return the default only when target is null , use: 如果您只想targetnull时返回默认null ,请使用:

let serve = target === null ? "Hello World" : target;

target , in your example is not null . target ,在您的示例中不为null It isn't anything: You haven't declared it at all. 没什么:您根本没有声明它。

 let target = null; let serve = target || "Hello World"; console.log(serve); 

Possibly you are thinking of the pattern: 您可能正在考虑这种模式:

 var serve = serve || "Hello World"; console.log(serve); 

Which: 哪一个:

  • Uses var to ensure that serve is a declared variable 使用var来确保serve是一个声明的变量
  • Assigns "Hello World" to serve is some previous code hasn't already assigned it a true value. 分配"Hello World"来服务是因为以前的一些代码尚未为其分配真值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM