JavaScript 空检查 [英] JavaScript null check

查看:38
本文介绍了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 ♦ 的回答中,maericsnwellnhof,即使没有为函数提供参数,它的参数变量也总是被声明.这个事实也证明了下面列表中的第一项是错误的.

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 !== 未定义.

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 after 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天全站免登陆