2017-04-22 82 views
0

我正在學習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 a tr 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看來,不可能在中途放棄內部地圖調用,它會返回整個數組。似乎循環對於這份工作來說可能會更好,或者我錯過了什麼?

+0

'圖()'需要的參數,讓你當前元素的索引,所以你可以使用和查看文本長度這樣https://開頭的jsfiddle .net/Lg0wyt9u/1816/ –

+0

@NenadVracar噢,我的意思是不添加整行,即數組到2d數組,而不是單元格。但我會盡力在小提琴上做到這一點。 –

+0

'return return $(this).text()|| undefined' – Thomas

回答

0

假設你發佈的是爲你工作...

如果你想第一td不是空的每一行的.text的代碼,使用CSS選擇器的組合可能是解決方案。

:first-child
:not
:empty

編輯
好了...我改進了一點。
看起來像有可以在一個空的td ... 一些空格所以我用regex來測試它。

下面是我用了新的東西:
:first
.test() JavaScript方法
.trim() JavaScript方法

而且CodePen在那裏我tryed它。

$(document).ready(function(){ 
    console.clear(); 
    console.log("loading..."); 

    var tRows = $('tr').map(function() { 
    return [$(this).find('td:first').map(function() { 
     var pattern = /^\s+$/; 
     if($(this).text()!="" && !pattern.test($(this).text())){ 
     return $(this).text().trim(); 
     } 
    }).get()] 
    }).get() 

    console.log(tRows) 
}); 

這個回報:[["blah1],[],[blah7]],在CodePen ...
如果你不想空單在中間:

CodePen

$(document).ready(function(){ 
    console.clear(); 
    console.log("loading..."); 

    var tRows = $('tr').map(function() { 
    var arr = [$(this).find('td:first').map(function() { 
     var pattern = /^\s+$/; 
     if($(this).text()!="" && !pattern.test($(this).text())){ 
     return $(this).text().trim(); 
     } 
    }).get()]; 

    if(arr[0]!=""){ 
     return arr; 
    } 
    }).get() 

    console.log(tRows) 
}); 

這回:[["blah1],[blah7]]





第2編輯
這也可以通過這種方式來實現。
(它意味着只有一個循環,代碼更易於閱讀)
見第3 CodePen

$(document).ready(function(){ 
    console.clear(); 
    console.log("loading..."); 

    var arr=[]; 
    var counter=0; 

    $('tr').each(function() { 
    var thisTDtext = [$(this).find("td").first().text().trim()]; 

    if(thisTDtext!=""){ 
     arr[counter] = thisTDtext; 
     counter++; 
    } 
    }); 

    console.log(JSON.stringify(arr)); 

}); 

這也返回:[["blah1],[blah7]]

+0

拋出:未捕獲錯誤:語法錯誤,無法識別的表達式:tr:first-child(td:not(:empty())) –

+0

好的......等等,我會在CodePen中試一下。 –

+0

我改進了一點...嘗試一下! –