JavaScript 空检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16672743/
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
JavaScript null check
提问by afsantos
I've come across the following code:
我遇到了以下代码:
function test(data) {
if (data != null && data !== undefined) {
// some code here
}
}
I'm somewhat new to JavaScript, but, from other questions I've been reading here, I'm under the impression that this code does not make much sense.
我对 JavaScript 有点陌生,但是,从我在这里阅读的其他问题来看,我的印象是这段代码没有多大意义。
You'll get an error if you access an undefined variable in any context other thantypeof
.
如果您在除typeof
.
Update:The (quote of the) answer above may be misleading. It should say ?an undeclared variable?, instead of ?an undefined variable?.
更新:上面的(引用)答案可能会产生误导。它应该说?一个未声明的变量?, 而不是? 一个未定义的变量?.
As I found out, in the answers by Ryan ?, maerics, and nwellnhof, even when no arguments are provided to a function, its variables for the arguments are always declared. This fact also proves wrong the first item in the list below.
正如我发现的,在Ryan的回答中?、maerics和nwellnhof,即使没有为函数提供参数,也始终声明其参数的变量。这个事实也证明了下面列表中的第一项是错误的。
From my understanding, the following scenarios may be experienced:
根据我的理解,可能会遇到以下场景:
The function was called with no arguments, thus makingdata
an undefined variable, and raising an error ondata != null
.The function was called specifically with
null
(orundefined
), as its argument, in which casedata != null
already protects the inner code, rendering&& data !== undefined
useless.The function was called with a non-null argument, in which case it will trivially pass both
data != null
anddata !== undefined
.
该函数在没有参数的情况下被调用,从而产生data
一个未定义的变量,并在 上引发错误data != null
。该函数被专门使用
null
(orundefined
) 作为其参数调用,在这种情况下,data != null
已经保护了内部代码,使其&& data !== undefined
变得无用。该函数是使用非空参数调用的,在这种情况下,它将轻松地同时传递
data != null
和data !== undefined
。
Q: Is my understanding correct?
问:我的理解正确吗?
I've tried the following, in Firefox's console:
我在 Firefox 的控制台中尝试了以下操作:
--
[15:31:31.057] false != null
[15:31:31.061] true
--
[15:31:37.985] false !== undefined
[15:31:37.989] true
--
[15:32:59.934] null != null
[15:32:59.937] false
--
[15:33:05.221] undefined != null
[15:33:05.225] false
--
[15:35:12.231] "" != null
[15:35:12.235] true
--
[15:35:19.214] "" !== undefined
[15:35:19.218] true
I can't figure out a case where the data !== undefined
afterdata != null
might be of any use.
我无法弄清楚data !== undefined
afterdata != null
可能有用的情况。
采纳答案by Ry-
An “undefined variable” is different from the value undefined
.
“未定义变量”与 value 不同undefined
。
An undefined variable:
一个未定义的变量:
var a;
alert(b); // ReferenceError: b is not defined
A variable with the value undefined
:
具有值的变量undefined
:
var a;
alert(a); // Alerts “undefined”
When a function takes an argument, that argument is always declared even if its value is undefined
, and so there won't be any error. You are right about != null
followed by !== undefined
being useless, though.
当一个函数接受一个参数时,即使它的值是 ,该参数也总是被声明undefined
,因此不会有任何错误。不过,你是对的,!= null
然后!== undefined
是无用的。
回答by maerics
In JavaScript, null
is a special singleton object which is helpful for signaling "no value". You can test for it by comparison and, as usual in JavaScript, it's a good practice to use the ===
operator to avoid confusing type coercion:
在 JavaScript 中,null
是一个特殊的单例对象,有助于发出“无价值”的信号。您可以通过比较来测试它,并且像在 JavaScript 中一样,使用===
运算符来避免混淆类型强制是一个很好的做法:
var a = null;
alert(a === null); // true
As @rynah mentions, "undefined" is a bit confusing in JavaScript. However, it's always safe to test if the typeof(x)
is the string "undefined", even if "x" is not a declared variable:
正如@rynah 提到的,“未定义”在 JavaScript 中有点令人困惑。但是,typeof(x)
即使“x”不是声明的变量,测试它是否是字符串“undefined”总是安全的:
alert(typeof(x) === 'undefined'); // true
Also, variables can have the "undefined value" if they are not initialized:
此外,如果变量未初始化,它们可以具有“未定义值”:
var y;
alert(typeof(y) === 'undefined'); // true
Putting it all together, your check should look like this:
把它们放在一起,你的支票应该是这样的:
if ((typeof(data) !== 'undefined') && (data !== null)) {
// ...
However, since the variable "data" is always defined since it is a formal function parameter, using the "typeof" operator is unnecessary and you can safely compare directly with the "undefined value".
但是,由于变量“data”始终是定义的,因为它是形式函数参数,因此无需使用“typeof”运算符,您可以安全地直接与“未定义的值”进行比较。
function(data) {
if ((data !== undefined) && (data !== null)) {
// ...
This snippet amounts to saying "if the function was called with an argument which is defined and is not null..."
这段代码相当于说“如果函数是用一个已定义且不为空的参数调用的......”
回答by nwellnhof
Q:The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.
问:该函数被无参数调用,从而使 data 成为未定义的变量,并在 data != null 上引发错误。
A:Yes, data
will be set to undefined. See section 10.5 Declaration Binding Instantiationof the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.
A:是的,data
会设置为undefined。参见规范的10.5 声明绑定实例化部分。但是访问未定义的值不会引发错误。您可能将此与在严格模式下访问未声明的变量混淆,这确实会引发错误。
Q:The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.
问:该函数是专门使用 null(或 undefined)作为参数调用的,在这种情况下 data != null 已经保护了内部代码,渲染 && data !== undefined 无用。
Q:The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.
问:该函数是使用非空参数调用的,在这种情况下,它将简单地传递 data != null 和 data !== undefined。
A:Correct. Note that the following tests are equivalent:
答:正确。请注意,以下测试是等效的:
data != null
data != undefined
data !== null && data !== undefined
See section 11.9.3 The Abstract Equality Comparison Algorithmand section 11.9.6 The Strict Equality Comparison Algorithmof the spec.
回答by Kamil Kie?czewski
In your case use data==null
(which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)
在您的情况下使用data==null
(这仅适用于 null 和 undefined - 在第二张图片上关注行/列 null-undefined)
function test(data) {
if (data != null) {
console.log('Data: ', data);
}
}
test(); // the data=undefined
test(null); // the data=null
test(undefined); // the data=undefined
test(0);
test(false);
test('something');
Here you have all (src):
在这里你有所有(src):
if
如果
==(its negation !=)
==(它的否定!=)
===(its negation !==)
===(它的否定!==)
回答by Kamil Kie?czewski
I think, testing variables for values you do not expect is not a good idea in general. Because the test as your you can consider as writing a blacklist of forbidden values. But what if you forget to list all the forbidden values? Someone, even you, can crack your code with passing an unexpected value. So a more appropriate approach is something like whitelisting - testing variables only for the expected values, not unexpected. For example, if you expect the data value to be a string, instead of this:
我认为,测试您不期望的值的变量通常不是一个好主意。因为您可以将测试视为编写禁止值的黑名单。但是如果你忘记列出所有禁止的值怎么办?有人,甚至你,都可以通过传递一个意想不到的值来破解你的代码。因此,更合适的方法类似于白名单——仅针对预期值测试变量,而不是意外。例如,如果您希望数据值是一个字符串,而不是这样:
function (data) {
if (data != null && data !== undefined) {
// some code here
// but what if data === false?
// or data === '' - empty string?
}
}
do something like this:
做这样的事情:
function (data) {
if (typeof data === 'string' && data.length) {
// consume string here, it is here for sure
// cleaner, it is obvious what type you expect
// safer, less error prone due to implicit coercion
}
}
回答by Kamil Kie?czewski
typeof foo === "undefined"
is different from foo === undefined
, never confuse them. typeof foo === "undefined"
is what you really need. Also, use !==
in place of !=
typeof foo === "undefined"
不同于foo === undefined
,永远不要混淆它们。typeof foo === "undefined"
是您真正需要的。此外,使用!==
代替!=
So the statement can be written as
所以语句可以写成
function (data) {
if (typeof data !== "undefined" && data !== null) {
// some code here
}
}
Edit:
编辑:
You can not use foo === undefined
for undeclared variables.
不能foo === undefined
用于未声明的变量。
var t1;
if(typeof t1 === "undefined")
{
alert("cp1");
}
if(t1 === undefined)
{
alert("cp2");
}
if(typeof t2 === "undefined")
{
alert("cp3");
}
if(t2 === undefined) // fails as t2 is never declared
{
alert("cp4");
}
回答by Kadiri
The simple way to do your test is :
进行测试的简单方法是:
function (data) {
if (data) { // check if null, undefined, empty ...
// some code here
}
}
回答by overflow
var a;
alert(a); //Value is undefined
var b = "Volvo";
alert(b); //Value is Volvo
var c = null;
alert(c); //Value is null