关于使用[].slice.call将伪数组转换成数组在不同浏览器中的兼容问题

使用[].slice.call的场景不外乎于两种地方,一种是将arguments转换成数组,另一种地方是将元素集合转换成数组。由于公司的项目一直是针对firefox开发,因此在进行转换时也没进行严格的测试,但这两天要将项目迁移到IE平台下,发现Ly.getByName出错,经过测试发现是IE9是正常,当为IE8-时就会出问题。而问题就出在[].slice.call(el, 0)处。通过以下浏览器的测试输出可以找到问题。

 1 <body>
 2 <input type="hidden" name="test" />
 3 <input type="hidden" name="test" />
 4 <input type="hidden" name="test" />
 5 <script type="text/javascript">
 6     var t = document.getElementsByName('test');
 7     
 8     for (var p in t) {
 9         document.write(p + ': ' + t[p] + '<br />');
10     }
11     
12     document.write('<br />');
13     
14     try {
15         document.write([].slice.call(t, 0));
16     } catch (e) {
17         document.write('浏览器不支持...');
18     }
19 </script>
20 </body>
Firefox下输出:

0: [object HTMLInputElement]
1: [object HTMLInputElement]
2: [object HTMLInputElement]
length: 3
item: function item() { [native code] }
namedItem: function namedItem() { [native code] }

[object HTMLInputElement],[object HTMLInputElement],[object HTMLInputElement]



IE9下输出:

test: [object HTMLCollection]
length: 3
item: function item() { [native code] } 
namedItem: function namedItem() { [native code] }

[object HTMLInputElement],[object HTMLInputElement],[object HTMLInputElement]



IE8下输出:

length: 3
test: [object HTMLCollection]
test: [object HTMLCollection]
test: [object HTMLCollection]

浏览器不支持...

从以上输出结果可以发现,FIREFOX下输出的三个test对象其实有下标注,而且还是使用的数字。在IE9下输出了一个test,后面跟一个数组,这块不知道为什么运行[].slice.call(t, 0)竟然也可以,望有知道的同学指点下。但IE8下可以看到返回的是三个同名的属性test,因此调用slice时执行失败。

原文地址:https://www.cnblogs.com/AUOONG/p/2730560.html