[英]how do I display(or call) the contents of an anonymous function that is defined inside of an array in javascript
I want to call ctx.fillRect(10, 10, 15, 5)
in the location where I specified it to do so ( Array[0]
) When I console.log(Array[0])
it shows the function inside of the array but it does not call the function when I specify the array's index. 我想在我指定的位置调用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);
}
You need to invoke the function using ()
您需要使用()
调用该函数
Array[0]()
Since the function doesn't have a return
there isn't much benefit in doing console.log(Array[0]())
which would display undefined
由于该函数没有return
因此执行console.log(Array[0]())
并显示undefined
不会有太多好处。
Functions can be stored in arrays. 函数可以存储在数组中。 For example we can store a function to say hello in an array: 例如,我们可以在数组中存储一个要打个招呼的函数:
var arr = [function(){return "hello";}];
now we have a function stored in arr[0] and 现在我们有一个函数存储在arr [0]中,
console.log(arr[0]);
displays something like function... 显示类似功能...
To call a function we use the call operator () 要调用函数,我们使用调用运算符()
console.log(arr[0]());
displays: hello 显示:你好
Keep in mind that Array is the name of a constructor... the constructor to create an array, so it is best not to reuse it as the name of an array. 请记住,Array是构造函数的名称...用于创建数组的构造函数,因此最好不要将其用作数组的名称。
Here is a code snippet that is similar to the code in your question. 这是一个与您的问题中的代码相似的代码片段。
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.