使用 .each 从表创建字符串,如何在每行后添加换行符

Creating string from table with .each, how to add a newline after each row?

本文关键字:换行符 添加 each 创建 字符串 使用      更新时间:2023-09-26

我正在使用以下javascript从表的选定单元格中获取数据:

var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true};
var data = [];
$j("#myTable tr").each(function(rowIndex) {
    $j(this).find("td").each(function(cellIndex) {
        if (cellIndexMapping[cellIndex])
            data.push($j(this).text()  );
    });
});
var fullCSV = data.join(", ");
console.log (fullCSV);

这使我的所有表元素都位于逗号分隔的数组中。 例如,如果我的表是

<th>| zero | one | two | three | four | five | </th>
---------------------------------------------
<tr>|  A   |  B  |  C  |  D    |  E   |  F   | </tr>
---------------------------------------------
<tr>|  G   |  H  |  I  |  J    |  K   |  L   | </tr>

我回来了 :

A,B,D,E,F,G,H,J,K,L

我需要的是每行之间的换行符"'n"。 所以我想要的结果看起来像:

A,B,D,E,F,'n G,H,J,K,L 'n

有什么想法吗?

var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true},
    data = [],
    finalData = [];
$j("#myTable tr").each(function(rowIndex) {
    data.push([]);
    $j(this).find("td").each(function(cellIndex) {
        if (cellIndexMapping[cellIndex])
            data[rowIndex].push( $j(this).text() );
    });
});
$j.each(data, function(i, e) {
    finalData.push( e.join(',') );
});
finalData.join("'n");

或者,您可以在每个循环中附加'n

var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true},
    finalData = '';
$j("#myTable tr").each(function(rowIndex) {
    var data = [];
    $j(this).find("td").each(function(cellIndex) {
        if (cellIndexMapping[cellIndex])
            data.push( $j(this).text() );
    });
    finalData += data.join(', ') + "'n";
});

看到这个小提琴:http://jsfiddle.net/kLsW5/

你只需要在外循环的末尾添加它:

var res = "";
$j("#myTable tr").each(function(rowIndex) {
    var data = [];
    $j(this).find("td").each(function(cellIndex) {
        if (cellIndexMapping[cellIndex])
            data.push($j(this).text()  );
    });
    res += data.join(", ") + "'n";
});

现在res保存最终值。

您确定要在第一行中使用尾随逗号吗?你不想要这样的东西吗:

A,B,D,E,F'nG,H,J,K,L'n

以下是使用 .map() [docs] 的一种方法:

var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true};    
var fullCSV = $j("#myTable tr").map(function() {
    return $j(this).find("td").map(function(cellIndex) {
        return cellIndexMapping[cellIndex] ? $j(this).text() : null;
    }).get().join(', ');
}).get().join(''n');