简体   繁体   中英

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.

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

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

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM