我已经创建了一个用于将表转换为JSON对象的应用程序,该应用程序运行正常,但问题是主体键首次出现一个空数组。
谁能告诉我一些
{"head":["Person Name","Person Name","Points","Price","Tax"],"body":[[],["Jill","Smith","50","150","41"],["Eve","Jackson","94","250","81"],["John","Doe","80","950","412"],["Adam","Johnson","67","750","941"]]}
我的脚本如下
$('#convert-table').click( function() {
try{
var myTable = [];
var myTr =[];
$('#example-table tr').each(function (i, tr) {
var myTd =[];
$('th', tr).each(function(j, th) {
myTr.push($.trim(th.innerHTML));
});
$('td', tr).each(function(j, td) {
if(td.innerHTML.indexOf("span") != -1){
var text = $(this).closest('td').find('span').text();
myTd.push($.trim(text));
}
else{
myTd.push($.trim(td.innerHTML));
}
});
myTable.push(myTd);
});
var headObj ={
head:myTr,
body:myTable
};
jsfiddle
最佳答案
尝试使用条件检查数组是否为空
更新:因为对于第一个TR,您只有th而不是td,这就是数组为空的原因。
例如
if(myTd.length > 0)
myTable.push(myTd);