use*_*339 16 javascript jquery
鉴于这种:
<a href="1">1</a>
<a href="2">2</a>
Run Code Online (Sandbox Code Playgroud)
这是一个返回href值数组的函数:
e = $('a').map(function(v) { return $(this).attr('href'); });
console.log(e);
Run Code Online (Sandbox Code Playgroud)
但它给出了
["1", "2", prevObject: x.fn.x.init[2], context: document, jquery: "1.10.2", constructor: function, init: function…]
Run Code Online (Sandbox Code Playgroud)
如何将其修改为仅返回原始数组["1","2"]?
and*_*lrc 30
这是因为jQuery.fn.map返回一个新的jQuery对象,你应该使用它jQuery.fn.get来获取一个数组:
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
Run Code Online (Sandbox Code Playgroud)
微优化:
如果您查看源代码,jQuery.fn.get您可以看到它指向您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 ] );
}
Run Code Online (Sandbox Code Playgroud)
所以你也可以打电话:
$('a').map(...).toArray();
Run Code Online (Sandbox Code Playgroud)