JavaScript空检查 [英] JavaScript null check

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

问题描述

我遇到了以下代码:

function test(data) {
    if (data != null && data !== undefined) {
        // some code here
    }
}

我对JavaScript有点陌生,但是从这里我一直在阅读的其他问题中,我给人的印象是这段代码没有多大意义.

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.

如果在除typeof之外的任何上下文中访问未定义的变量,都会收到错误消息.

You'll get an error if you access an undefined variable in any context other than typeof.

更新:以上答案(的引用)可能会引起误解.应该说«一个未声明的变量»,而不是«一个未定义的变量».

Update: The (quote of the) answer above may be misleading. It should say «an undeclared variable», instead of «an undefined variable».

我发现,在 Ryan♦ 的答案中, nwellnhof ,即使没有为函数提供任何参数,也始终会声明其用于参数的变量.这个事实也证明下面列表中的第一项是错误的.

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.

据我了解,可能会遇到以下情况:

From my understanding, the following scenarios may be experienced:

  • 该函数不带任何参数调用,因此使data成为未定义的变量,并在data != null上引发错误.

  • The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

该函数专门以null(或undefined)作为参数调用,在这种情况下,data != null已经保护了内部代码,使&& data !== undefined无效.

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.

使用非空参数调用该函数,在这种情况下,它将同时传递data != null data !== undefined.

The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

问:我的理解正确吗?

我已经在Firefox的控制台中尝试了以下操作:

I've tried the following, in Firefox's console:

--
[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

我不知道data !== undefined 之后 data != null可能有用的情况.

I can't figure out a case where the data !== undefined after data != null might be of any use.

推荐答案

未定义的变量"与值undefined不同.

An "undefined variable" is different from the value undefined.

一个未定义的变量:

var a;
alert(b); // ReferenceError: b is not defined

值为undefined的变量:

var a;
alert(a); // Alerts "undefined"

当一个函数接受一个参数时,即使它的值是undefined,也总是声明该参数,因此不会有任何错误.您对!= null是正确的,但随后!== 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.

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

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