我正在學習jquery,想出了將html表格數據存儲到二維數組的問題。而不是使用嵌套循環,我正在尋找jQuery的功能,這將允許我這樣做。我發現this method似乎在做這項工作。有選擇地將表格數據存儲到2d數組
var tRows = $('tr').map(function() {
return [$(this).find('td').map(function() {
return $(this).text()
}).get()]
}).get()
console.log(tRows)
I'd like to know, how I can use a condition, in the given code, to check if the first
td
of atr
is empty or not (or some other condition in general) and thus not add that row to the final array.
編輯:
讀經this fiddle的意見和建設,我現在有
var tRows = $('tr').map(function() {
var arr = $(this).find('td').map(function() {
return $(this).text()
}).get();
if (arr[0].length) return[arr];
}).get()
這工作有點,但我希望來檢查條件在內的地圖並返回一個NULL而不是整個數組。從discussion here看來,不可能在中途放棄內部地圖調用,它會返回整個數組。似乎循環對於這份工作來說可能會更好,或者我錯過了什麼?
'圖()'需要的參數,讓你當前元素的索引,所以你可以使用和查看文本長度這樣https://開頭的jsfiddle .net/Lg0wyt9u/1816/ –
@NenadVracar噢,我的意思是不添加整行,即數組到2d數組,而不是單元格。但我會盡力在小提琴上做到這一點。 –
'return return $(this).text()|| undefined' – Thomas