[英]Javascript add item to current array
I am trying to add an item to a current array. 我正在尝试将项添加到当前数组。
var arrayValues = new Array();
arrayValues.push("Value 1");
arrayValues.push("Value 2");
arrayValues = document.getElementsByTagName('a');
arrayValues.push("Value 3");
By doing this way I get a error, and I dont get value 1 and value 2, after getting the hyperlink collection when I try to add a new item it throws Error: Object doesn't support this property or method which is the push method. 通过这种方式,我得到一个错误,我得到超值集合,当我尝试添加它抛出的新项目后,我得到值1和值2错误:对象不支持此属性或方法,这是推送方法。
What is happening to the array after the collection of hyperlinks is assigned ? 收集超链接后,数组发生了什么? How can I add a new item to it ?
如何添加新项目?
Did you mean arrayValues.push(document.getElementsByTagName('a'));
你的意思是
arrayValues.push(document.getElementsByTagName('a'));
? ?
Otherwise, you're assigning the NodeList
returned by getElementsByTagName()
, which overwrites the array you had just pushed values into. 否则,您将分配
getElementsByTagName()
返回的NodeList
,它会覆盖您刚刚将值推入的数组。
Side note: there's no reason to use new Array()
here. 旁注:这里没有理由使用
new Array()
。 Just write var arrayValues = [];
只需写
var arrayValues = [];
. 。
If you want to push all <a>
elements to the array, you have to convert the NodeList to an array first. 如果要将所有
<a>
元素推送到数组,则必须先将NodeList转换为数组。 Most people use Array.prototype.slice.call(nodelist)
. 大多数人使用
Array.prototype.slice.call(nodelist)
。
Once you have an array, you can then use array.push
in conjunction with function.apply
to push them in one call. 一旦有了数组,就可以将
array.push
与function.apply
结合使用,在一次调用中推送它们。
The resulting code looks like: 生成的代码如下所示:
var arrayValues = [];
arrayValues.push("Value 1");
arrayValues.push("Value 2");
arrayValues.push.apply(arrayValues, Array.prototype.slice.call(document.getElementsByTagName('a')));
arrayValues.push("Value 3");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.