use*_*546 8 javascript arrays html-object
我正在尝试合并两个由html对象组成的数组.出于某种原因,使用.concat()对我不起作用.
这是一个简单的笔来演示这个问题:http://codepen.io/anon/pen/kIeyB
注意:我尝试搜索远程类似的东西但发现没有回答我的问题.
我认为你可以使用for循环来做这个方式,但我宁愿不重新发明轮子.
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
//alert(items.length);
var items2 = x.getElementsByClassName("two");
//alert(items2.length);
items = items.concat(items2);
//alert(items.length);
Run Code Online (Sandbox Code Playgroud)
items和items2是nodeList或HTMLCollection对象,而不是阵列.它们不包含.concat()方法.它们具有.length属性和支持[x]索引,但它们没有其他数组方法.
将它们复制到实际数组中的常见解决方法如下:
// convert both to arrays so they have the full complement of Array methods
var array1 = Array.prototype.slice.call(x.getElementsByClassName("one"), 0);
var array2 = Array.prototype.slice.call(x.getElementsByClassName("two"), 0);
Run Code Online (Sandbox Code Playgroud)
这也可以这样做:
var allitems = [];
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("one"));
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("two"));
Run Code Online (Sandbox Code Playgroud)
该allitems变量将是一个Array包含所有类one&元素的 JavaScript two。
| 归档时间: |
|
| 查看次数: |
5420 次 |
| 最近记录: |