2013-07-05 60 views
14

鑑於此:

<a href="1">1</a> 
<a href="2">2</a> 

這裏是返回HREF值的數組的函數:

e = $('a').map(function(v) { return $(this).attr('href'); }); 
console.log(e); 

但它給

["1", "2", prevObject: x.fn.x.init[2], context: document, jquery: "1.10.2", constructor: function, init: function…] 

我怎麼能修改此只返回一個原始數組[「1」,「2」]?

+0

當你的'console.log'指出,這些都不是您的href值。 –

+2

這就是爲什麼你不應該完全信任控制檯輸出(至少'console.log','console.dir'應該沒問題)。由於jQuery對象是一個*數組類似的*對象,所以'console.log'將它顯示爲數組。其他瀏覽器可能會顯示不同的輸出。 –

+0

確定公平的電話。任何建議如何做到這一點返回一個原始數組? (修改了我的問題以反映David的觀點) – user537339

回答

28

這是因爲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 

微優化:

如果你看一下源代碼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 ]); 
} 

所以,你也可以撥打:

$('a').map(...).toArray();