Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does $(...).map() return?

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"]?

like image 604
user537339 Avatar asked Jul 05 '13 14:07

user537339


People also ask

What does the map function return?

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.

What does map return in Javascript?

Return Value: It returns a new array and elements of arrays are result of callback function.

Does .map have to return something?

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.

What map entries return?

The Map. entries() method returns the [key, value] pairs of all the elements of a map in the order of their insertion.


1 Answers

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();
like image 56
Andreas Louv Avatar answered Oct 02 '22 14:10

Andreas Louv