据我了解,IE8 可以访问 Array.prototype.slice
方法。然而,当我尝试调用它以将 NodeList
转换为数组时,它给我错误 Array.prototype.slice: 'this' is not a JavaScript object
。 You 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/