最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript add item to current array - Stack Overflow

programmeradmin4浏览0评论

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.

What is happening to the array after the collection of hyperlinks is assigned ? How can I add a new item to it ?

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.

What is happening to the array after the collection of hyperlinks is assigned ? How can I add a new item to it ?

Share Improve this question edited Sep 13, 2013 at 22:04 Thaddeus Albers 4,1925 gold badges36 silver badges43 bronze badges asked Mar 8, 2011 at 3:49 VinayVinay 2211 gold badge6 silver badges13 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

Did you mean arrayValues.push(document.getElementsByTagName('a'));?

Otherwise, you're assigning the NodeList returned by getElementsByTagName(), which overwrites the array you had just pushed values into.

Side note: there's no reason to use new Array() here. Just write var arrayValues = [];.

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

Once you have an array, you can then use array.push in conjunction with function.apply to push them in one call.

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");
发布评论

评论列表(0)

  1. 暂无评论