p5.js | createNumberDict()函数
createNumberDict()函数用于使用给定数据创建 p5.NumberDict 实例。数据可以单独传递一个键值对或使用对象作为值的集合。
句法:
createNumberDict(key, value)
或者
createNumberDict(object)
参数:
- key:它指定用作字典中的键的数字。
- value:它指定用作字典中的值的数字。
- object:它指定用作字典的对象。
返回值:它返回一个带有给定数据的p5.NumberDict对象。
下面的程序说明了 p5.js 中的createNumberDict()函数:
示例 1:
function setup() {
createCanvas(500, 200);
textSize(20);
// Creating a number dictionary
// with the given key and value pair
let mydict = createNumberDict("19", "1999");
// Accessing the data using the data property
text('The dictionary has the following data under "19":', 20, 20);
text(mydict.data["19"], 20, 40);
// Checking if a key exists in the dictionary
text('The dictionary has the "25" key present:', 20, 80);
text(mydict.hasKey("19"), 20, 100);
text('The dictionary has the "100" key present:', 20, 140);
text(mydict.hasKey("100"), 20, 160);
}
输出:
示例 2:
function setup() {
createCanvas(600, 200);
textSize(20);
let squaresObject = {
2: 4,
3: 9,
4: 16,
5: 25
}
// Creating a number dictionary
// with the above object
let mydict = createNumberDict(squaresObject);
// Accessing the data using the data property
text('The dictionary has the following data under key "2":', 20, 20);
text(mydict.data["2"], 20, 40);
text('The dictionary has the following data under key "4":', 20, 80);
text(mydict.data["4"], 20, 100);
text('The dictionary has the following data under key "5":', 20, 140);
text(mydict.data["5"], 20, 160);
}
输出:
在线编辑器: https://editor.p5js.org/
环境设置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
参考: https://p5js.org/reference/#/p5/createNumberDict