用javascript连接html对象数组

Concatenating html object arrays with javascript

本文关键字:对象 数组 html 连接 javascript      更新时间:2023-09-26

我正在尝试合并两个由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);

itemsitems2nodeListHTMLCollection对象,不是数组。它们不包含.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变量将是一个单独的javascript Array,包含所有类为one &two .

你所拥有的是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>

document.getElementsByClassName不返回数组。它返回具有长度属性的NodeList。