JavaScript 的类型函数是否检查空值

Does JavaScript's typeof function check for null

本文关键字:检查 空值 是否 函数 类型 JavaScript      更新时间:2023-09-26

javascripts typeof表达式会检查空吗?

var test = {};
console.log(typeof test['test']);//"undefined"
var test = null;
console.log(typeof test['test']);//TypeError: test is null

显然,但是如果typeof null是一个对象,为什么会有错误?

编辑:
我知道如何避免类型错误,并且null没有属性,但我想知道是否有对typeof行为的解释。

var test = { test: null };
console.log(typeof test['test']);// will be object

您的代码会引发异常,因为您正在读取 null 的属性,如下所示:

null['test']

问题是您正在尝试访问 test 的元素,但testnull而不是数组/对象。因此,以下代码会抛出错误:test['test'] .

如果您直接null传递它,typeof将正常工作。例如,使用 node.js 控制台:

> typeof null
'object'

你要求它读取null的属性"test",这毫无意义,错误基本上是告诉你"test是null ->无法读取null的属性"test"。

你应该只是做typeof test而不是typeof test['test'],我不确定你为什么要做后一种方式。

你可以试试你的测试作为

typeof (test && test['test']) 

这样你就可以避免类型错误