PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] How to iterate over the rows of a table with p5js using table.setNum()

 August 28, 2022     csv, export-to-csv, javascript, p5.js     No comments   

Issue

function saveAsCSV() {
  
  let simulationOutput = new p5.Table();

  let newRow = simulationOutput.addRow();
  
  simulationOutput.addColumn("Total Population");
  simulationOutput.addColumn("Human Population");
  simulationOutput.addColumn("Predator Population");
  simulationOutput.addColumn("Prey Population");
  simulationOutput.addColumn("Food Population");

  for(var i = 1; i<totalDynamic.length; i++){
    simulationOutput.addRow().setNum("Total Population", int(totalDynamic[i]));
  }
  
  for(let j = 1; j<predDynamic.length; j++){
    simulationOutput.setNum(j,1, int(predDynamic[j]));
    j++;
  }
  
  save(simulationOutput, month()+"/"+day()+"_T:"+hour()+":"+minute()+":"+second()+"_Simulation_Output.csv");
}

I'm looking to save the outputs of a simulation to a .csv file, but I can't seem to iterate over the rows of the table using the for loop. I'm using p5.js

for(let j = 1; j<predDynamic.length; j++){
    simulationOutput.setNum(j,1, int(predDynamic[j]));
    j++;}

I get the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'setNum')
    at o.default.Table.setNum (p5.min.js:3:593463)
    at o.default.Element.saveAsCSV (predator_prey.js:255:22)
    at o.default.Element.<anonymous> (p5.min.js:3:429692)

The problem is with iterating using the j, but I can't see how this returns undefined?


Solution

You get this error because totalDynamic.length < predDynamic.length

A row is added for each item in totalDynamic and not predDynamic. But when there are more items in predDynamic than totalDynamic, The p5.Table() doesn't recognize the rows because they haven't been initialized yet. Possible solution:

for(let j = 1; j<predDynamic.length; j++){
   if(simulationOutput.rows.length <= j) simulationOutput.addRow();
   simulationOutput.setNum(j,1, int(predDynamic[j]));
   j++;
}


Answered By - Henhen1227
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing