📜  p5.js | p5.Table addColumn() 方法

📅  最后修改于: 2022-05-13 01:56:49.988000             🧑  作者: Mango

p5.js | p5.Table addColumn() 方法

p5.js 中 p5.Table 的addColumn() 方法用于向表对象添加新列。该方法接受一个参数,该参数用于指定列的标题,以便以后可以轻松引用它。它是一个可选值,不指定标题会使新列的标题为空。
句法:

addColumn( [title] )

参数:此函数接受如上所述和如下所述的单个参数:

  • title:它是一个字符串,表示新列的标题。它是一个可选参数。

以下示例说明了 p5.js 中的addColumn()函数
示例 1:

javascript
function setup() {
  createCanvas(500, 300);
  textSize(16);
  
  saveTableBtn = createButton("Save Table");
  saveTableBtn.position(30, 50);
  saveTableBtn.mouseClicked(saveToFile);
  
  text("Click on the button to save table to csv", 20, 20);
    
  // Create the table
  table = new p5.Table();
  
  // Add two columns
  // using addColumn()
  table.addColumn("author");
  table.addColumn("language");
  
  // Add two rows
  let newRow = table.addRow();
  newRow.setString("author", "Dennis Ritchie");
  newRow.setString("language", "C");
  
  newRow = table.addRow();
  newRow.setString("author", "Bjarne Stroustrup");
  newRow.setString("language", "C++");
  
  text("The table has " + table.getColumnCount() + 
       " columns", 20, 100);
}
  
function saveToFile() {
  saveTable(table, "saved_table.csv");
}


javascript
function setup() {
  createCanvas(600, 300);
  textSize(16);
  
  addColBnt = createButton("Add Column");
  addColBnt.position(30, 20);
  addColBnt.mouseClicked(addNewCol);
  
  // Create the table
  table = new p5.Table();
}
  
function addNewCol() {
  let colName = "Random Column " + floor(random(1, 100));
  
  // Add the given column to table
  table.addColumn(colName);
}
  
function draw() {
  clear();
  
  // Show the total number of columns
  // and current column names
  text("The table has " + table.getColumnCount() + 
       " columns", 20, 60);
  text("The columns are", 20, 80);
  for (let i = 0; i < table.columns.length; i++) {
    text(table.columns[i], 20, 100 + i * 20);
  }
}


输出:

addCol-保存文件

示例 2:

javascript

function setup() {
  createCanvas(600, 300);
  textSize(16);
  
  addColBnt = createButton("Add Column");
  addColBnt.position(30, 20);
  addColBnt.mouseClicked(addNewCol);
  
  // Create the table
  table = new p5.Table();
}
  
function addNewCol() {
  let colName = "Random Column " + floor(random(1, 100));
  
  // Add the given column to table
  table.addColumn(colName);
}
  
function draw() {
  clear();
  
  // Show the total number of columns
  // and current column names
  text("The table has " + table.getColumnCount() + 
       " columns", 20, 60);
  text("The columns are", 20, 80);
  for (let i = 0; i < table.columns.length; i++) {
    text(table.columns[i], 20, 100 + i * 20);
  }
}

输出:

addCol-btn

在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5.Table/addColumn