Javascript - TypeError: Object [object Object] 没有方法'forEach'



我正在代码中编写遥测函数。我正在使用 MDN 链接中提到的 Performance.getEntriesByType() 函数 - https://developer.mozilla.org/en-US/docs/Web/API/Performance/getEntriesByType。根据链接,它提到该方法返回性能条目对象/空列表的列表。但是,当我在 window.performance.getEntriesByType(type) 方法的返回值上调用"forEach"方法时,我收到以下错误

TypeError: Object [object Object] has no method 'forEach'

几个疑问:

  1. 为什么我得到错误"forEach"没有方法?
  2. 错误消息中的对象 [对象对象] 意味着什么?

这意味着您正在尝试在没有该方法的对象上调用forEach()方法forEach()方法。 forEach() 是在 Array.prototype 上实现的(意味着所有数组都有此方法),一些浏览器在 DOM nodeList 对象上实现它。但是,您要么尝试在另一种对象上使用它,要么在不支持它的浏览器中使用它。

performance.getEntriesByType()返回一个list,它与实现forEach()Array不同。

您引用的页面显示了如何循环访问window.performance.getEntriesByType()调用的结果列表。

  // Use getEntries() to iterate through the each entry
  var p = performance.getEntries();
  for (var i=0; i < p.length; i++) {
    log("Entry[" + i + "]");
    check_PerformanceEntry(p[i]);
  }

我个人在 android 设备上遇到了一个错误,问题出在依赖项的代码中,所以我无法更改它。我使用此填充物来解决此问题:

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = function (callback, thisArg) {
        thisArg = thisArg || window;
        for (var i = 0; i < this.length; i++) {
            callback.call(thisArg, this[i], i, this);
        }
    };
}

最新更新