用javascript连接html对象数组
我正在尝试合并由html对象组成的两个数组。出于某种原因,使用.concat()对我来说不起作用 这里有一支简单的笔来演示这个问题: 注意:我试图搜索一些稍微相似的东西,但没有找到任何答案 我想你可以用for循环的ole方式来实现,但我不想重新发明轮子用javascript连接html对象数组,javascript,arrays,html-object,Javascript,Arrays,Html Object,我正在尝试合并由html对象组成的两个数组。出于某种原因,使用.concat()对我来说不起作用 这里有一支简单的笔来演示这个问题: 注意:我试图搜索一些稍微相似的东西,但没有找到任何答案 我想你可以用for循环的ole方式来实现,但我不想重新发明轮子 var x = document.getElementById("hello"); var items = x.getElementsByClassName("one"); //alert(items.length); var items2 =
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);
document.getElementsByClassName
不返回数组。
它返回具有长度属性的节点列表。
项和项2
是节点列表
或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);
您拥有的是HTMLCollections,虽然其行为类似于数组,但不是数组。请看这里:
..集合是表示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]]
<div class="one"></div>
以及:
将返回:
[HTMLCollection[1], HTMLCollection[1]]
<div class="one"></div>
也可以这样做:
var allitems = [];
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("one"));
allitems = Array.prototype.concat.apply(allitems, x.getElementsByClassName("two"));
allitems
变量将是一个javascript数组
,包含类为one
&two的所有元素
请说明实际问题,并包含重现问题的有效示例。codepen清楚地说明了我遇到的问题,因为第6行将导致执行错误。谢谢你的回答,你说的一切都是正确的。对于我的处境;然而,我试图连接多个数组,这样我就可以在一个循环中横穿它们。对于试图操作多个节点列表的用户来说,使用您建议的多维数组并不是最合适、最有用的方法。谢谢,这非常有效!出于好奇,您能否解释slice.call()以及“0”参数的用途。@user3718546:.@user3718546-.slice()
适用于任何具有.length
且支持从0
到length-1
索引的对象(其中包括nodeList
和HTMLCollection,以及arguments`object等。)因此,我们使用Array.prototype
中的.slice()
方法调用该方法,但将nodeList
作为对象传递给它,以便使用.call()
。0
是.slice()
的第一个参数,意思是从开头开始浅拷贝。如果您阅读.slice()
和.call()
的文档,您将看到它们是如何协同工作的。