Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用javascript连接html对象数组_Javascript_Arrays_Html Object - Fatal编程技术网

用javascript连接html对象数组

用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 =

我正在尝试合并由html对象组成的两个数组。出于某种原因,使用.concat()对我来说不起作用

这里有一支简单的笔来演示这个问题:

注意:我试图搜索一些稍微相似的东西,但没有找到任何答案

我想你可以用for循环的ole方式来实现,但我不想重新发明轮子

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()
的文档,您将看到它们是如何协同工作的。