Convert table to array in JavaScript without using jQuery

后端 未结 4 1591
离开以前
离开以前 2020-12-15 10:02

I need to convert the table grid i created into an multidimensional array according to the content inside the table. Array would be in format like:

 var arra         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 11:03

    Presuming your table is something like the one below, you can convert that into an array of arrays using the rows collection of the table and cells collection of the rows:

    function tableToArray(table) {
      var result = []
      var rows = table.rows;
      var cells, t;
    
      // Iterate over rows
      for (var i=0, iLen=rows.length; i
    onetwothree
    onetwothree
    onetwothree

    Or if like concise code, use some ES5 goodness:

    function tableToArray(table) {
      var result  = [].reduce.call(table.rows, function (result, row) {
          result.push([].reduce.call(row.cells, function(res, cell) {
              res.push(cell.textContent);
              return res;
          }, []));
          return result;
      }, []);
      return result;
    }
    

提交回复
热议问题