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 |1 Answer
Reset to default 31It 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
版权声明:本文标题:javascript - What exactly does $(...).map() return? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738547229a2096660.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
console.log
points out, those are not your href values. – David Hedlund Commented Jul 5, 2013 at 14:09console.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