使用typeof vs ===检查未声明的变量会产生不同的结果 [英] Using typeof vs === to check undeclared variable produces different result

查看:95
本文介绍了使用typeof vs ===检查未声明的变量会产生不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个未声明的变量并使用 typeof ,它告诉我它是 undefined
但是如果我然后使用 if(qweasdasd === undefined)检查它会引发异常。

If I have an undeclared variable and use typeof it tells me it's undefined. But if I then check it using if (qweasdasd === undefined) it throws an exception.

我不明白这种行为,因为如果第一次告诉 undefined ,那么第二次检查应该评估为 if(undefined === undefined ),为什么抛出一个ReferenceError异常?

I don't understand this behavior, because if the first tells undefined, then the second check should evaluate to if (undefined === undefined), why does it throw a ReferenceError exception?

推荐答案

typeof 看起来像一个函数调用,但它不是 - 它是一个运算符。允许运营商违反规则。 typeof(qweasdasd)不假设 qweasdasd 存在;是否存在以及它是什么 typeof 是否存在要发现。但是,当您测试 qweasdasd === undefined 时,您使用 qweasdasd 作为值,并且当您使用JS时抱怨使用您尚未赋值的变量。

typeof looks like a function call, but it is not - it is an operator. Operators are allowed to break rules. typeof(qweasdasd) does not assume qweasdasd exists; whether it exists or not and what it is is what typeof exists to discover. However, when you test qweasdasd === undefined, you are using qweasdasd as a value, and JS complains when you use a variable that you haven't assigned a value to.

这篇关于使用typeof vs ===检查未声明的变量会产生不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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