p5.Table matchRows() 方法
p5.js 中 p5.Table 的matchRows() 方法用于查找与给定正则表达式匹配的所有行。它以数组的形式返回对匹配行的引用。该方法用于搜索行的列可以指定为参数。
句法:
matchRows( regexp, [column] )
参数:此方法接受上面提到的两个参数,如下所述:
- regexp:它是一个 String 或 RegExp 对象,指定要匹配的正则表达式。
- column:它是一个字符串或数字,表示列的名称或列的 ID。它是一个可选参数。
返回值:此方法返回与给定正则表达式匹配的 p5.TableRow 对象数组。
下面的示例说明了 p5.js 中的match Rows() 方法:
例子:
function setup() {
createCanvas(500, 300);
textSize(16);
matchQueryInput =
createInput();
matchQueryInput.position(30, 40);
getColBtn =
createButton("Get the matching row");
getColBtn.position(30, 70);
getColBtn.mouseClicked(getMatchedResults);
// Create the table
table = new p5.Table();
// Add two columns
table.addColumn("name");
table.addColumn("id");
// Add some rows to the table
let newRow = table.addRow();
newRow.setString("name", "mary");
newRow.setString("id", 21);
newRow = table.addRow();
newRow.setString("name", "marco6");
newRow.setString("id", 27);
newRow = table.addRow();
newRow.setString("name", "tunisia 4");
newRow.setString("id", 32);
newRow = table.addRow();
newRow.setString("name", "user 23");
newRow.setString("id", 32);
newRow = table.addRow();
newRow.setString("name", "admin");
newRow.setString("id", 45);
newRow = table.addRow();
newRow.setString("name", "mikasa");
newRow.setString("id", 23);
showTable();
}
function getMatchedResults() {
clear();
let matchQuery =
matchQueryInput.value();
if (matchQuery != "") {
// Match the query in the column of 'name'
matchResults =
table.matchRows(new RegExp(matchQuery),
'name');
if (matchResults.length > 0) {
text("The rows that matches the " +
"query is", 20, 120);
for (let i = 0; i < matchResults.length; i++) {
// Display the matched value
text(matchResults[i].arr[0], 20, 140 + i * 20);
text(matchResults[i].arr[1], 120, 140 + i * 20);
}
}
else text("No Results Found", 20, 120);
} else {
text("The query string is empty", 20, 120);
}
text("Enter a string to match it in " +
"the 'name' column table", 20, 20);
}
function showTable() {
clear();
// Display the total rows present in the table
text("There are " + table.getRowCount() +
" rows in the table", 20, 120);
for (let r = 0; r < table.getRowCount(); r++)
for (let c = 0; c < table.getColumnCount(); c++)
text(table.getString(r, c),
20 + c * 100, 140 + r * 20);
text("Enter a string to match it in " +
"the 'name' column table", 20, 20);
}
输出:
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5.Table/matchRows