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很新,但是,从我在这里读过的其他问题来看,我的印象是这段代码没有多大意义。)
In particular, this answer states that(特别是, 这个答案说明了这一点)
You'll get an error if you access an undefined variable in any context other than typeof
.(如果在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.
(正如我在Ryan? , maerics和nwellnhof的回答中所发现的那样,即使没有为函数提供参数,也始终声明其参数的变量。)
This fact also proves wrong the first item in the list below.(这个事实也证明了下面列表中的第一项是错误的。)
From my understanding, the following scenarios may be experienced:
(根据我的理解,可能会遇到以下情况:)
The function was called with no arguments, thus making data
an undefined variable, and raising an error on data != null
.(调用该函数时没有参数,从而使data
成为未定义的变量,并在data != null
上引发错误data != null
。)
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
无用。)
The function was called with a non-null argument, in which case it will trivially pass both data != null
and data !== undefined
.
(该函数使用非null参数调用,在这种情况下,它将平凡传递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
after data != null
might be of any use.
(我无法弄清楚data !== undefined
data != null
后的情况 data != null
可能有用。)
ask by afsantos translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…