![](/img/trans.png)
[英]p5.js 27646: Uncaught TypeError: Cannot read property '0' of undefined
[英]“Uncaught TypeError: Cannot read property 'bind' of undefined” on p5.js
我正在使用p5.js來與精靈進行按鈕交互。 我只是有一個關於通過for循環創建按鈕的快速問題。 我知道我可以輕松地為4個按鈕中的每個按鈕創建單獨的對象,但是我想看看它如何以這種方式工作以使代碼更短。
我想讓每個按鈕在for循環中以遞增的i調用一個函數“ puton(i)”,以便每個按鈕可以執行不同的操作(在我的情況下,這是穿不同的衣服)。 但是,我得到這個錯誤:
Uncaught TypeError: Cannot read property 'bind' of undefined.
我不太了解參數在javascript中是如何工作的,因此我可能會遇到這種非常錯誤的情況,因此,對於更有效的方法(除了對每個按鈕進行硬編碼之外)的一些見識也將受到贊賞。
提前致謝!
var hat, shirt, pants, shoes;
function setup(){
createCanvas(500, 300);
background(155);
var clothes = ["Hat", "Shirt", "Pants", "Shoes"]; // Just to make the code clean.
for(var i = 0; i < clothes.length; i++){
var change = createButton('Put on ' + clothes[i]);
change.position(10, i*30 + 60);
change.mousePressed(puton(i));
}
}
function puton(i){
console.log(i); //To test, "0" gets printed, but after that it crashes.
}
.mousePressed()
將函數作為其參數,而不是函數調用。 官方文檔中有一個很好的例子: https : //p5js.org/reference/#/p5.Element/mousePressed
這將在您的情況下工作:
change.mousePressed(puton);
甚至這樣:
change.mousePressed(function(e) {
console.log(e);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.