Reputation: 1831
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"]?
Upvotes: 17
Views: 2456
Reputation: 47099
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();
Upvotes: 31