2013-01-07 11 views
13

我要總結所有彩車在一個陣列jQuery是添加prevObject:數組

我這樣做的鉻控制檯

$("tr.project_hours").find("td.number").map(function(i,v) 
{return parseFloat($(v).attr("data-time")) 
}) 

我得到的時候

[0, 0, 0, 0, 0, 0, 0] 

這是什麼我想要

但是,在我的代碼中我有更多的$(「tr.project_hours」),我想分別將它們相加。 所以,我做

$("tr.project_hours").each(function(){ 
    row = $(this).find('td.total') 
    row.html(sumInputsIn($(this).find("td.number").map(function(i,v){ 
    return parseFloat($(v).attr("data-time"))}))); 
    }) 

( 'td.total')是應顯示的結果列。問題是最後一個代碼在控制檯中返回這個結果

[0, 0, 0, 0, 0, 0, 0, prevObject: jQuery.fn.jQuery.init[7], context: <tr>] 

所以結果是臭名昭着的NaN。

爲什麼我會在我的數組中獲得prevObject?我怎麼能重構擺脫它?

+1

並且您的數據是什麼? –

+0

換句話說,向我們展示一個HTML樣本。 – LarsH

回答

2

這應該開展預期的結果:

$("tr.project_hours").each(function(index, element) { 
    var row = $(this).find('td.total'); 
    var total = 0; 
    $(this).find("td.number").each(function (index, element) { 
     total += parseFloat($(v).attr("data-time")); 
    }); 
    row.html(total); 
}); 

jQuery map執行for (item in array)這顯然如果你得到這些密鑰不被hasOwnProperty()篩選。在這種情況下,你需要自己編寫邏輯我猜。

+0

請參閱steveukx的答案,爲jQuery添加更多這些道具的更好解決方案 – chris

32

在jQuery集合上調用map的返回類型是另一個jQuery集合。如果只想訪問地圖中使用的函數的結果,則需要使用.toArray()來返回底層數組:

var numbersArray = $("tr.project_hours").find("td.number").map(function(i,v) 
    {return parseFloat($(v).attr("data-time")) 
}).toArray(); 
+0

這使得所有tr.project_hours錶行都有很長的數組。我需要將它們分開 –

+0

我明白了,這個答案更關注爲什麼你在使用'jQuery.fn.map'的結果中看到'prevObject'。 – steveukx