p5.Table addRow() 方法
p5.js 中 p5.Table 的 addRow () 方法用于向 table 对象添加新的一行数据。此方法默认创建一个空行。这可以通过存储对新行对象的引用然后使用set()方法设置行中的值来使用。或者,可以将 p5.TableRow 对象作为参数包含在该方法中。这将直接复制给定的行并将其添加到表中。
句法:
addRow( [row] )
参数:此函数接受如上所述和如下所述的单个参数:
- row:它是一个 p5.TableRow 对象,指定要添加到表中的行。它是一个可选参数。
下面的示例说明了 p5.js 中的 addRow ()函数:
示例 1:
javascript
function setup() {
createCanvas(500, 300);
textSize(16);
addRowBtn = createButton("Add Row");
addRowBtn.position(30, 40);
addRowBtn.mouseClicked(addNewRow);
// Create the table
table = new p5.Table();
table.addColumn("author");
table.addColumn("langauge");
}
function addNewRow() {
// Create new row object
let newRow = table.addRow();
// Add data to it using setString()
newRow.setString("author", "Author " + floor(random(1, 100)));
newRow.setString("langauge", "Langauge " + floor(random(1, 100)));
}
function draw() {
clear();
// Show the total number of rows
text("The table has " + table.getRowCount() + " rows", 20, 20);
// Show the columns
text("Author", 20, 80);
text("Language", 120, 80);
// Show the table with the rows
for (let r = 0; r < table.getRowCount(); r++)
for (let c = 0; c < table.getColumnCount(); c++)
text(table.getString(r, c), 20 + c * 100, 120 + r * 20);
}
javascript
function setup() {
createCanvas(500, 300);
textSize(16);
addRowBtn = createButton("Add Row");
addRowBtn.position(30, 40);
addRowBtn.mouseClicked(addNewRow);
// Create the table
table = new p5.Table();
table.addColumn("author");
table.addColumn("book");
}
function addNewRow() {
// Create a new TableRow object
let tableRow = new p5.TableRow("Author X, Book Y", ",");
// Add the TableRow to table
table.addRow(tableRow);
}
function draw() {
clear();
// Show the total number of rows
text("The table has " + table.getRowCount() + " rows", 20, 20);
// Show the columns
text("Author", 20, 80);
text("Book", 120, 80);
// Show the table with the rows
for (let r = 0; r < table.getRowCount(); r++)
for (let c = 0; c < table.getColumnCount(); c++)
text(table.getString(r, c), 20 + c * 100, 120 + r * 20);
}
输出:
示例 2:
javascript
function setup() {
createCanvas(500, 300);
textSize(16);
addRowBtn = createButton("Add Row");
addRowBtn.position(30, 40);
addRowBtn.mouseClicked(addNewRow);
// Create the table
table = new p5.Table();
table.addColumn("author");
table.addColumn("book");
}
function addNewRow() {
// Create a new TableRow object
let tableRow = new p5.TableRow("Author X, Book Y", ",");
// Add the TableRow to table
table.addRow(tableRow);
}
function draw() {
clear();
// Show the total number of rows
text("The table has " + table.getRowCount() + " rows", 20, 20);
// Show the columns
text("Author", 20, 80);
text("Book", 120, 80);
// Show the table with the rows
for (let r = 0; r < table.getRowCount(); r++)
for (let c = 0; c < table.getColumnCount(); c++)
text(table.getString(r, c), 20 + c * 100, 120 + r * 20);
}
输出:
在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5.Table/addRow