javascript错误& Cannot read property 'foo'null"而且

What is the difference between the javascript errors "Cannot read property 'foo' of null" and "null is not an object"

本文关键字:foo quot 而且 null property 错误 Cannot read javascript      更新时间:2023-09-26

我们正在记录javascript错误,其中一个错误消息已经出现了很多是null is not an object,例如TypeError: null is not an object (evaluating 'foo[bar]')。在我搜索此错误并试图复制错误时,我不断得到Cannot read property 'foo' of null错误。我无法找出一种方法来做一些导致null is not an object错误的事情。

这两个错误之间的区别是什么?当一个错误被调用而不是另一个错误被调用时,有哪些例子?

当你给一个对象赋null值并试图访问它的任何属性时,你会得到null不是一个对象。

所以,基本上如果你尝试在一个null值的对象上调用任何函数会给出这个错误:

  • null在Safari中不是对象

  • 在Chrome中无法读取null属性

  • TypeError: obj[1] is null in Firefox

由hindmost的回复是正确的,有不同的消息取决于浏览器。给定以下代码:

var a = null, b = 5;
a[b];

Chrome将给出错误Uncaught TypeError: Cannot read property '5' of null,而Safari将给出错误TypeError: null is not an object (evaluating 'a[b]')

差别不大。该消息取决于脚本运行的浏览器/环境。如:-

var x = null;
console.log(x.length);

对于chrome,消息将是

cannot read property 'length' of null
safari

'null' is not an object (evaluating 'c.length')