检查JavaScript变量是否为空的最可靠方法是什么? [英] What's the most reliable way to check if a JavaScript variable is null?
问题描述
如果我想检查变量是否为空或不存在,那么可靠的方法是什么?
What is the mos reliable way if I want to check if the variable is null or is not present?.
有不同的例子:
if (null == yourvar)
if (typeof yourvar != 'undefined')
if (undefined != yourvar)
推荐答案
以上都不是。
你不想用 ==
或其中的各种因为它执行类型强制。如果你真的想检查是否显式为null,请使用 ===
运算符。
You don't want to use ==
, or a variety thereof, because it performs type coercion. If you really want to check whether something is explicitly null, use the ===
operator.
然后,您的问题可能显示您的要求缺乏明确性。你具体是指 null
吗?或未定义
计数? myVar === null
肯定会告诉你变量是否为空,这是你问的问题,但这真的是你想要的吗?
Then again, your question shows perhaps some lack of clarity of your requirements. Do you actually mean null
specifically; or does undefined
count too? myVar === null
will certainly tell you if the variable is null, which is the question you asked, but is this really what you want?
请注意,这个问题。它不是直接复制,但它涵盖了非常相似的原则。
Note that there's a lot more information in this SO question. It's not a direct duplicate, but it covers very similar principles.
这篇关于检查JavaScript变量是否为空的最可靠方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!