p5.Table trim() 方法
p5.js 中 p5.Table 的trim() 方法用于从作为字符串的表值中删除前导和尾随空格。空格包括字符串中可能存在的空格或制表符。可以指定特定列以仅从该列中删除空格。但是,如果未指定任何列,则修剪所有列和行中的值。
句法:
trim( [column] )
参数:此函数接受如上所述和如下所述的单个参数:
- column:它是一个字符串或整数,指定要修剪的列的列名或ID。它是一个可选参数。
下面的示例说明了 p5.js 中的trim() 方法:
示例 1:
function setup() {
createCanvas(500, 300);
textSize(16);
trimBtn =
createButton("Trim the table");
trimBtn.position(30, 40);
trimBtn.mouseClicked(trimTable);
// Create the table
table = new p5.Table();
// Add two columns
table.addColumn("name");
table.addColumn("rating");
// Add some rows to the table
let newRow = table.addRow();
newRow.setString("name", "Eren ");
newRow.setString("rating", " Good");
newRow = table.addRow();
newRow.setString("name", " Erwin");
newRow.setString("rating", "Excellent ");
newRow = table.addRow();
newRow.setString("name", "Marco");
newRow.setString("rating", " OK");
newRow = table.addRow();
newRow.setString("name", " Mikasa ");
newRow.setString("rating", "Very Good ");
showTable();
}
function trimTable() {
// Trim all the columns and rows
table.trim();
// Redraw the table
showTable();
}
function showTable() {
clear();
// Display the rows present in the table
for (let r = 0; r < table.getRowCount(); r++)
for (let c = 0; c < table.getColumnCount(); c++)
text(table.getString(r, c),
20 + c * 140,
100 + r * 20);
text("Click on the button to trim the table",
20, 20);
}
输出:
示例 2:
function setup() {
createCanvas(500, 300);
textSize(16);
trimBtn =
createButton("Trim the table");
trimBtn.position(30, 40);
trimBtn.mouseClicked(trimTable);
// Create the table
table = new p5.Table();
// Add two columns
table.addColumn("name");
table.addColumn("rating");
// Add some rows to the table
let newRow = table.addRow();
newRow.setString("name", "Eren ");
newRow.setString("rating", " Good");
newRow = table.addRow();
newRow.setString("name", " Erwin");
newRow.setString("rating", "Excellent ");
newRow = table.addRow();
newRow.setString("name", "Marco");
newRow.setString("rating", " OK");
newRow = table.addRow();
newRow.setString("name", " Mikasa ");
newRow.setString("rating", "Very Good ");
showTable();
}
function trimTable() {
// Trim only the 'name' column
table.trim('name');
// Redraw the table
showTable();
}
function showTable() {
clear();
// Display the rows present in the table
for (let r = 0; r < table.getRowCount(); r++)
for (let c = 0; c < table.getColumnCount(); c++)
text(table.getString(r, c),
20 + c * 140, 100 + r * 20);
text("Click on the button to trim the table",
20, 20);
}
输出:
在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5.Table/trim