javascript - "Array.prototype.slice: ' IE8中这个' is not a JavaScript object"错误

标签 javascript arrays dom prototype nodelist

据我了解,IE8 可以访问 Array.prototype.slice 方法。然而,当我尝试调用它以将 NodeList 转换为数组时,它给我错误 Array.prototype.slice: 'this' is not a JavaScript objectYou can check it out here ,或在此处查看我的代码:

HTML

<div id="test">Test</div>

JavaScript

var divs = document.getElementsByTagName('div');
divs = Array.prototype.slice.call(divs);
console.log(divs);

这是怎么回事?

最佳答案

更新:A NodeList可以在某些方面被视为一个数组 - 在你可以遍历它之前你实际上不需要对它做任何特殊的事情,例如:

var aDivs = [];
for (var = i = 0; i < divs.length; i++) {
    aDivs.push(divs[i]);
}

这将创建一个数组,其中包含运行 document.getElementsByTagName() 时匹配的所有节点

参见 this question有关为什么 slice 在某些浏览器中使用 NodeList 而在其他浏览器中不使用的原因的完整解释,但它归结为规范中的这句话:

Whether the slice function can be applied successfully to a host object is implementation-dependent.

关于javascript - "Array.prototype.slice: ' IE8中这个' is not a JavaScript object"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317752/

相关文章:

java - 多个数组的公共(public)元素但不使用列表

php - 列出目录中的所有文件夹并插入数组

javascript - 获取 HTMLDivElement 的 id

jquery - 使用 jQuery 删除 <html> 上方和下方的标记 </html>

javascript - 每次 HttpClient 调用时,Angular 6 都将 withCredentials 设置为 true

javascript - Chart.js 2.1.3 中的自定义图例

c - 指向多维数组的指针数组

javascript - 如何获得一个 react 组件树,就像它在 react 开发工具中显示的那样?

javascript - 使用 AJAX 刷新莫里斯图

javascript - 插件 gulp-babel : Plugin/Preset files are not allowed to export objects, 中的错误仅起作用