Javascript 这个判断在Array.prototype.filter中是否必不可少

Javascript 这个判断在Array.prototype.filter中是否必不可少,javascript,arrays,Javascript,Arrays,我发现developer.mozilla网站上显示的许多方法没有必要的判断。URL: 您可以转到“Polyfill”部分 始终存在如下代码所示的判断: Array.prototype.filter = function(fun /*, thisArg */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); ... } 不仅是筛选方法,还包括Array

我发现developer.mozilla网站上显示的许多方法没有必要的判断。
URL:

您可以转到“Polyfill”部分

始终存在如下代码所示的判断:

Array.prototype.filter = function(fun /*, thisArg */)
{
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();
    ...
}
不仅是筛选方法,还包括Array.prototype.every()、Array.prototype.map()。
例如:

Array.prototype.map = function (fun /*, thisp */) {
   if (this === void 0 || this === null) { throw TypeError(); 
   ...
}
我不知道在什么情况下,条件的结果将返回true,然后抛出“TypeError”。
在我看来,这个判断不是必要的,应该删除。 你怎么认为?
这个判断是为了什么?这个是指数组本身

void 0
返回
undefined
且不能被覆盖(而
undefined
can-pre ES5)

该检查用于确定原型方法是否用于实际存在的对象,即未定义或为空

如果您查看最新的polyfill,他们只需使用:

if (this == null) {
   throw new TypeError(" this is null or not defined");
}
因为
null==undefined
true

我不知道在什么情况下,情况的结果会返回 true,然后抛出一个“TypeError”

答复:

Array.prototype.filter = function(fun /*, thisArg */){
  console.log('okay',this==null);
}
Array.prototype.filter.call(null);
Array.prototype.filter.call(undefined);

“判断”可能不是你要找的词。你是说“条件”吗?是的,我是说“条件”谢谢你的回答。但我不明白你只是使用了一个调用方法,它如何证明该条件将返回true?@edmond它可以用于类似数组的对象,例如:getElementsByTagName添加条件,你就会看到它是true我看到了你的编辑。我在调试模式下试用了chrome。但是'this==null'仍然返回false。因为“this”指的是窗口对象。@edmond因为getElementByTagName返回一个类似数组的对象,该对象具有长度和[index],但不从数组继承(它没有筛选方法),所以必须使用array.prototype。filter.call(objectReturnedFromGetElements,…我使用getElementsByTagName进行了测试,但条件仍然返回false。感谢您的响应。我发现MDN的最新polyfill已更新为您所看到的内容。我认为,“undefined.filter”或“null.filter”不会变成数组。prototype.filter(),因此条件不是必需的。