2016-03-01 32 views
4

我有以下代碼:jQuery的地圖()返回對象,而不是陣列

var selectedTitles = $("#js-otms-titles-table .select_title :checkbox:checked").map(function() { 
    return $(this).attr('data-titleId'); 
}); 
console.log("Selected titles"); 
console.log(selectedTitles); 

我期望的結果將是一個數組。但我收到的對象如:

Object["55a930cd27daeaa6108b4f68", "55a930cd27daeaa6108b4f67"] 

是否有一個特殊的標誌傳遞給函數?在docs他們正在談論數組作爲返回值。我錯過了什麼?

的jQuery 1.11.2

回答

4

$(selector).map()總是返回jQuery對象。

要想從jQuery對象數組使用get()

var selectedTitles = $("#js-otms-titles-table .select_title :checkbox:checked").map(function() { 
    return $(this).attr('data-titleId'); 
}).get(); 
1

你需要調用.get()對最終結果。 jQuery的.map()函數返回一個jQuery對象(有時可能很方便)。 .get()將獲取它所構建的底層數組。

http://api.jquery.com/map/

+0

http://api.jquery.com/map/和http://api.jquery.com/jquery.map/有什麼區別? ?我有點困惑。 – Tamara

+2

一個在jQuery對象(通常是元素)上工作,另一個在普通對象或數組上。 – Scimonster

0
var a = array(1, 2, 3); 
var f = function() { return do_something_with_each(this); }; 

$.map(a, f) - 陣列 - 排列出

$(selector).map(f) - 在jQuery對象 - jQuery對象了

$(selector).map(f).get() - jQuery對象in - array out(自jQuery 1.0以來)

$(selector).map(f).toArray() - jQuery對象in-array out(自jQuery 1.4以來)

相關問題