Unable to render an array into table after splice and unshift in Javascript

时间秒杀一切 提交于 2020-01-06 13:09:04

问题


I am not sure if I am doing some mistake or is it a default behaviour. I am using splice/unshift to add a new element on top of a 2d array and then try to render that array to a table.

  for (var i = 0; i < arr1[i].length; i++) {
      for (var j = 0; j < arr1.length; j++) {
          var r = arr1[j][i];
          dt(r);
      }
      dttop(i);
  }

  function dt(x) {
      if (isFinite(x) == true) {
          numeric++;
      } else {
          str++;
      }
  }

  function dttop(x) {
      if (numeric > str)
          arr1.splice(0, 0, "number");
      else
          arr1.splice(0, 0, "string");
  }
  alert(arr1); // alert--1  
   // render the result into html table
  s = '<table border=0>';
  for (var i = 0; i < arr1.length; i++) {
      s = s + '<tr>';
      for (var j = 0; j < arr1[i].length; j++) {
          s = s + '<td><font size="1" face="Verdana">' + arr1[i][j] + '</font></td>';
      }
      s = s + '</tr>';
  }
  s = s + '</table>';
  renderArea.innerHTML = s;

So, when I use javascript splice() or unshift(). I get an output like this

But, if I do alert 1 then it gives me result like this

which proves that it is adding the extra bits from splice function but not rendering as html..

Please help


回答1:


From what I can see you are using .splice() to add the string "number" or "string" to the start of the arr1 array. Doing this means that as you loop through to add the values the code tries to access an index of the strings (arr1[i][j]), resulting in undefined.




回答2:


I am using splice/unshift to add a new element on top of a 2d array and then try to render that array to a table.

The splice() method returns an array containing the elements that were removed from the original array. If you want to prepend values given a two dimensional array:

var num_arr = [[1,2,3]];

A simpler solution would be:

json_arr = JSON.stringify(num_arr).replace("[[","[0,[");

And rendering to a table would be:

function rowMaster(value,index)
  {
  return "<tr><td>value</td></tr>".replace("value",value);
  }

function parseFarce(value,index)
  {
  if(typeof value == "number") return "<th>value</th>".replace("value",value);

  else if(delete value.length === false && delete value[-1] === true && JSON.stringify(([]).constructor().valueOf()) === "[]") 
    {
    return value.map(rowMaster);
    }

  else
    {
    return value;
    }
  }

JSON.parse(json_arr).map(parseFarce);

References

  • JSON.parse Examples


来源:https://stackoverflow.com/questions/23173003/unable-to-render-an-array-into-table-after-splice-and-unshift-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!