Given this:
<a href="1">1</a>
<a href="2">2</a>
Here is a function to return an array of href values:
e = $('a').map(function(v) { return $(this).attr('href'); });
console.log(e);
But it gives
["1", "2", prevObject: x.fn.x.init[2], context: document, jquery: "1.10.2", constructor: function, init: function…]
How can I modify this to only return a raw array ["1", "2"]?
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable.
Return Value: It returns a new array and elements of arrays are result of callback function.
map() method allows you to loop over every element in an array and modify or add to it and then return a different element to take that elements place. However . map() does not change the original array. It will always return a new array.
The Map. entries() method returns the [key, value] pairs of all the elements of a map in the order of their insertion.
It is because jQuery.fn.map
returns a new jQuery Object, you should use jQuery.fn.get
to get an array:
var a = $('a').map(function(v, node) {
// v is the index in the jQuery Object,
// you would maybe like to return the domNode or the href or something:
// return node.href;
return v;
}).get(); // <-- Note .get() converts the jQuery Object to an array
Micro optimization:
If you look at the source code for jQuery.fn.get
you can see that it points you to jQuery.fn.toArray
:
function ( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
}
So you can also call:
$('a').map(...).toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With