[英]Concatenating html object arrays with javascript
我正在尝试合并两个由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);
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);
这也可以这样做:
var allitems = [];
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("one"));
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("two"));
allitems
变量将是一个包含所有具有one
和two
类的元素的javascript Array
。
document.getElementsByClassName
不返回数组。 它返回具有length属性的NodeList。
你所拥有的是HTMLCollections,它虽然表现得像数组,但不是数组。 请参见: https : //developer.mozilla.org/en/docs/Web/API/HTMLCollection :
..集合是一个表示DOM节点列表的对象。
在您的情况下,您可以将这些对象连接在一起成为一个新数组:
var itemsnew;
var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
var items2 = x.getElementsByClassName("two");
itemsnew = Array.prototype.concat.call(items, items2);
现在,如果你:
console.log(itemsnew);
将返回:
[HTMLCollection[1], HTMLCollection[1]]
和:
console.log(itemsnew[0][0]);
将返回:
<div class="one"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.