Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript';s函数类型检查是否为空_Javascript - Fatal编程技术网

JavaScript';s函数类型检查是否为空

JavaScript';s函数类型检查是否为空,javascript,Javascript,javascriptstypeofexpression是否检查空值 var test = {}; console.log(typeof test['test']);//"undefined" var test = null; console.log(typeof test['test']);//TypeError: test is null 显然,如果typeof null是一个对象,那么为什么会出现错误呢 编辑: 我知道如何避免类型错误,而且null没有属性,但我想知道typeof的行为有

javascripts
typeof
expression是否检查空值

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
的元素,但
test
null
而不是数组/对象。所以下面的代码抛出一个错误:
test['test']

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

> typeof null
'object'

您要求它读取null的属性“test”,这是没有意义的,错误基本上是告诉您“testisnull->不能读取null的属性“test”


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

你可以试着做你自己的测试

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

这样可以避免TypeError

因为第一个测试为null
null
没有“test”成员,试图访问它是非法的问题是您试图读取
null['test']
的val,您可以检查null的类型,但不能访问null的属性,因为null没有属性。事实上,您可以有一行代码,上面写着:“test['test'];”(并没有实际的值操作),它仍然会抛出一个错误。