如何显示(或调用)在 javascript 中的数组内部定义的匿名函数的内容
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>
我想在我指定的位置调用 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>