javascript - 使用javascript连接html对象数组

标签 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);

最佳答案

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);

关于javascript - 使用javascript连接html对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24133231/

相关文章:

javascript - 在子组件中将多个 this.props 属性分配给新变量一次时出错

javascript - 重画svg时如何避免闪烁?

javascript - 使用 on() 将参数传递给函数

C - 带有函数内 malloc 的 typedef 结构的动态数组

java - 在 Java 中调整数组大小会抛出 OutOfMemoryError

javascript - 如何更改 base64 应用程序/pdf 文件名?

javascript - 处理 Knex pg 数据库错误的正确方法是什么

c - 数组的动态分配

javascript - 从 &lt;iframe&gt; 或 <object> 中获取变量的值

html - 使用对象时如何更改鼠标悬停时的 SVG 描边颜色