admin管理员组

文章数量:1196940

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

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

Share Improve this question edited Jul 5, 2013 at 14:16 user537339 asked Jul 5, 2013 at 14:06 user537339user537339 1,8312 gold badges15 silver badges19 bronze badges 3
  • As your console.log points out, those are not your href values. – David Hedlund Commented Jul 5, 2013 at 14:09
  • 2 That's why you should never completely trust the console output (at least console.log, console.dir should be fine). Since a jQuery object is an array-like object, console.log displays it as array. Other browser might show a different output. – Felix Kling Commented Jul 5, 2013 at 14:12
  • OK fair call. Any suggestions on how to do this to return a raw array? (Have modified my question to reflect David's point) – user537339 Commented Jul 5, 2013 at 14:17
Add a comment  | 

1 Answer 1

Reset to default 31

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();

本文标签: javascriptWhat exactly does ()map() returnStack Overflow