Javascript add item to current array
Asked Answered
R

2

11

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 ?

Rondarondeau answered 8/3, 2011 at 3:49 Comment(0)
K
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 = [];.

Karee answered 8/3, 2011 at 3:52 Comment(1)
And NodeList isn't an Array, though it is "array-like."Fonzie
J
2

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");
Jablonski answered 8/3, 2011 at 3:58 Comment(3)
You don't need to apply the call to push. arrayValues is already an array, and a call to arrayValues.push() will execute the right function (push) in the right scope (arrayValues).Karee
I actually want to send multiple arguments to .push(). For example, var a=[], b=[2,3];, if you a.push(1);a.push(b);a.push(4), then a is [1,[2,3],4]. However, if you use a.push.apply(a,b);, you will get [1,2,3,4]. That's the expected behavior of this answer: push all <a> elements to an existing array. You can also say that it's a version of a = a.concat(b);.Jablonski
Okay, that makes more sense. In which case, why not just use concat()?Karee

© 2022 - 2024 — McMap. All rights reserved.