Javascript Javascript将项目添加到当前数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5228105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript add item to current array
提问by Vinay
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,当我尝试添加一个新项目时获取超链接集合后,它抛出错误:对象不支持此属性或方法,即 push 方法.
What is happening to the array after the collection of hyperlinks is assigned ? How can I add a new item to it ?
分配超链接集合后数组发生了什么?如何向其中添加新项目?
回答by Matt Ball
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.
否则,您将分配NodeList
返回的 by getElementsByTagName()
,它会覆盖您刚刚将值推入的数组。
Side note: there's no reason to use new Array()
here. Just write var arrayValues = [];
.
旁注:没有理由在new Array()
这里使用。只是写var arrayValues = [];
。
回答by Thai
If you want to push all <a>
elements to the array, you have to convert the NodeList to an array first. Most people use Array.prototype.slice.call(nodelist)
.
如果要将所有<a>
元素推送到数组,则必须先将 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");