有选择地将表格数据存储到2d数组
我正在学习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看来,不可能在中途放弃内部地图调用,它会返回整个数组。似乎循环对于这份工作来说可能会更好,或者我错过了什么?
假设你发布的是为你工作...
如果你想第一td
不是空的每一行的.text
的代码,使用CSS选择器的组合可能是解决方案。
编辑
好了...我改进了一点。
看起来像有可以在一个空的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 ...
如果你不想空单在中间:
$(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]]
抛出:未捕获错误:语法错误,无法识别的表达式:tr:first-child(td:not(:empty())) –
好的......等等,我会在CodePen中试一下。 –
我改进了一点...尝试一下! –
'图()'需要的参数,让你当前元素的索引,所以你可以使用和查看文本长度这样https://开头的jsfiddle .net/Lg0wyt9u/1816/ –
@NenadVracar噢,我的意思是不添加整行,即数组到2d数组,而不是单元格。但我会尽力在小提琴上做到这一点。 –
'return return $(this).text()|| undefined' – Thomas