如何检查变量是否为空? [英] How to check if a variable is not null?

查看:209
本文介绍了如何检查变量是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以下是JavaScript中检查变量是否不是 null 的两种方法,但我很困惑哪种方法最好使用。

I know that below are the two ways in JavaScript to check whether a variable is not null, but I’m confused which is the best practice to use.

我应该这样做:

if (myVar) {...}

if (myVar !== null) {...}


推荐答案

它们不等同。如果 myVar truthy ,则第一个将执行 if 语句后面的块(即评估如果 myVar 是<$ c以外的任何值,则第二个将执行该条件的 true $ c> null 。

They are not equivalent. The first will execute the block following the if statement if myVar is truthy (i.e. evaluates to true in a conditional), while the second will execute the block if myVar is any value other than null.

JavaScript中唯一不真实的值是以下(又名 falsy 值) ):

The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):


  • null

  • undefined

  • 0

  • (空字符串)

  • false

  • NaN

  • null
  • undefined
  • 0
  • "" (the empty string)
  • false
  • NaN

这篇关于如何检查变量是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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