[英]how do I display(or call) the contents of an anonymous function that is defined inside of an array in javascript
我想在我指定的位置調用ctx.fillRect(10, 10, 15, 5)
( Array[0]
)當我console.log(Array[0])
它在數組,但是當我指定數組的索引時它不會調用該函數。
function translate1() {
var ctx = canvas.getContext("2d");
var Array = [
function() {ctx.fillRect(10, 10, 15, 5)}
];
console.log(Array[0]); // displays as expected here
Array[0]; // I want the function to be called here
ctx.transform(1, 0, 0, 1, 0, 20);
Array[0]; // and again here
ctx.transform(1, 0, 0, 1, 0, 20);
ctx.fillRect(10, 10, 15, 5);
ctx.transform(1, 0, 0, 1, 0, 20);
ctx.fillRect(10, 10, 15, 5);
ctx.transform(1, 0, 0, 1, 0, 20);
ctx.fillRect(10, 10, 15, 5);
ctx.transform(1, 0, 0, 1, 0, 20);
}
您需要使用()
調用該函數
Array[0]()
由於該函數沒有return
因此執行console.log(Array[0]())
並顯示undefined
不會有太多好處。
函數可以存儲在數組中。 例如,我們可以在數組中存儲一個要打個招呼的函數:
var arr = [function(){return "hello";}];
現在我們有一個函數存儲在arr [0]中,
console.log(arr[0]);
顯示類似功能...
要調用函數,我們使用調用運算符()
console.log(arr[0]());
顯示:你好
請記住,Array是構造函數的名稱...用於創建數組的構造函數,因此最好不要將其用作數組的名稱。
這是一個與您的問題中的代碼相似的代碼片段。
function draw() { let canvas = document.getElementById("mycanvas"); let ctx = canvas.getContext("2d"); let arr = [ function() {ctx.fillRect(10, 10, 25, 50)} ]; console.log(arr[0]); // log out the function ctx.fillStyle = "red"; arr[0](); // call or execute the function ctx.stroke(); } draw();
<canvas id="mycanvas" height='100' width='100'></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.