How to store functions into an array and loop thro

2019-08-04 19:08发布

问题:

function canvasApp() {

if (!canvasSupport()) {
         return;
    }

function drawScreen() {


    context.font ="13px sans";

    context.fillStyle = "#000";
    context.beginPath();
    context.arc(p1.x,p1.y,9,0,Math.PI*2,true);
    context.closePath();
    context.fill();         
    context.fillStyle = "#FFFFFF";
    context.fillText("1",p1.x-2,p1.y+2);

    context.fillStyle = "#000";
    context.beginPath();
    context.arc(p2.x,p2.y,9,0,Math.PI*2,true);
    context.closePath();
    context.fill();         
    context.fillStyle = "#FFFFFF";
    context.fillText("2",p2.x-2, p2.y+2);

    context.fillStyle = "#000";
    context.beginPath();
    context.arc(p3.x,p3.y,9,0,Math.PI*2,true);
    context.closePath();
    context.fill();         
    context.fillStyle = "#FFFFFF";
    context.fillText("3",p3.x-2, p3.y+2);

    context.fillStyle = "#000";
    context.beginPath();
    context.arc(p4.x,p4.y,9,0,Math.PI*2,true);
    context.closePath();
    context.fill();         
    context.fillStyle = "#FFFFFF";
    context.fillText("4",p4.x-2, p4.y+2);


}

function drawScreen2() {

    //draw the points

    context.font ="13px sans";

    context.fillStyle = "#000";
    context.beginPath();
    context.arc(p9.x,p9.y,9,0,Math.PI*2,true);
    context.closePath();
    context.fill();         
    context.fillStyle = "#FFFFFF";
    context.fillText("9",p9.x-2,p9.y+2);

    context.fillStyle = "#000";
    context.beginPath();
    context.arc(p10.x,p10.y,9,0,Math.PI*2,true);
    context.closePath();
    context.fill();         
    context.fillStyle = "#FFFFFF";
    context.fillText("10",p10.x-2, p10.y+2);
}

var p1 = {x:668, y:220};
var p2 = {x:610, y:370};
var p3 = {x:565, y:490};
var p4 = {x:696, y:220};
var p5 = {x:750, y:370};
var p6 = {x:800, y:490};
var p7 = {x:635, y:415};
var p8 = {x:725, y:415};

var p9 = {x:635, y:415};
var p10 = {x:725, y:415};


theCanvas = document.getElementById('canvasOne');
context = theCanvas.getContext('2d');

setInterval(drawScreen, 513);   
setInterval(drawScreen2, 765);
}

in the above code i want to store drawscreen() and drawsscreen2() functions into an array and loop through to display points of each function seperately for an action.. how do i do this can anyone help me with this?

jsfiddle.net/karthikchandran/bn4kgov4 ..chk this demo when i click the next button the next function simply runs..i want all the functions i an loop and iterate one at a time when next button is clicked ..

回答1:

How to store functions into an array:

var arrayOfFunctions = [];
arrayOfFunctions.push(function1);
arrayOfFunctions.push(function2);

How to loop through each function and run it:

Variant 1:

for (var key in arrayOfFunctions) {
    arrayOfFunctions[key](); // run your function
}

Variant 2 (the same):

for (var i = 0; i < arrayOfFunctions.length; ++i) {
    arrayOfFunctions[i](); // run your function
}

Variant 3 (the same, but .forEach is not supported by IE <= 8 version):

arrayOfFunctions.forEach(function(func){
     func(); // run your function
});

Variant 4 (the same, but crossbrowser, require jQuery):

$.each(arrayOfFunctions, function(index, func) {
     func(); // run your function
});


回答2:

Iterate over an array of functions and call them with arguments

Iteration

   myFunctions.forEach(function(row){
     row.fx.apply(null, row.arguments);
   });

Usage example:

  function add(a, b){return a + b;}
  function sub(a, b){return a - b;}

  var myFunctions = [
      {fx: add, arguments:[2,5]},
      {fx: sum, arguments: [10,3]}
  ];

  myFunctions.forEach(function(row){
    row.fx.apply(null, row.arguments);
  });

Further explanation

There are three different methods to call function in JavaScript

  • Direct Invoke add(1,3);
  • Using function.call add.call(thisContext, 1, 3)
  • Using function.apply add.apply(thisContext, [1, 3]) (same as call but it takes array of arguments, Remember hint: a in apply for array )


回答3:

You also can do [object] like this:

var myObject = {
    fun1: function(){
        console.log(1);
    },

    fun2: function(){
        console.log(2);
    }
};

myObject.fun3 = function() {
    console.log(3);
};

for (var i in myObject) {
    myObject[i]();
}

Hope it can help you~



回答4:

After first button-press and after 10 button-press's:

I guess I would take a direct approach...

  1. Create an array of javascript objects. Each object defines a text and it's positioning.

    var pArray=[];
    pArray.push({text:'1',x:668, y:220});
    pArray.push({text:'2',x:610, y:370});
    ...
    
  2. Create a function that uses 1 object to draw the text at its specified position.

    function drawCircleText(p){
        context.fillStyle = "#000";
        context.beginPath();
        context.arc(p.x,p.y,9,0,Math.PI*2,true);
        context.closePath();
        context.fill();         
        context.fillStyle = "#FFFFFF";
        context.fillText(p.text,p.x-2, p.y+2);
    }
    
  3. When the user clicks a button, call the drawing function with the next object.

    // variable to hold the index of the next object to display
    var nextIndex=0;
    
    // when the user clicks the button
    $('#next').click(function(){
        // make sure we're not out of new text bubbles
        if(nextIndex>=pArray.length){alert('No more!');return;}
        // display the next text bubble
        drawCircleText(pArray[nextIndex]);
        // increment the index for next time
        nextIndex++;
    });
    

Example code and a Demo:

var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");

// remove this...it's just so the demo will show the
// results which are far to the right
context.translate(-500,-200);

// Create an array of objects
// The each object defines text and its positioning
var pArray=[];
pArray.push({text:'1',x:668, y:220});
pArray.push({text:'2',x:610, y:370});
pArray.push({text:'3',x:565, y:490});
pArray.push({text:'4',x:696, y:220});
pArray.push({text:'5',x:750, y:370});
pArray.push({text:'6',x:800, y:490});
pArray.push({text:'7',x:635, y:415});
pArray.push({text:'8',x:725, y:415});
pArray.push({text:'9',x:635, y:415});
pArray.push({text:'10',x:725, y:415});

// variable to hold the index of the next object to display
var nextIndex=0;

// when the user clicks the button
$('#next').click(function(){
  // make sure we're not out of new text bubbles
  if(nextIndex>=pArray.length){alert('No more!');return;}
  // display the next text bubble
  drawCircleText(pArray[nextIndex]);
  // increment the index for next time
  nextIndex++;
});


// Create an array that accepts the object definition
// and draws the text bubble
function drawCircleText(p){
  context.fillStyle = "#000";
  context.beginPath();
  context.arc(p.x,p.y,9,0,Math.PI*2,true);
  context.closePath();
  context.fill();         
  context.fillStyle = "#FFFFFF";
  context.fillText(p.text,p.x-2, p.y+2);
}
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id='next'>Next</button><br>
<canvas id="canvas" width=900 height=500></canvas>

By the way...

The nice thing about defining your bubble-texts in a javascript array is that if you ever need to save/restore those definitions you can easily convert the objects into text using:

// this string can easily be saved in a database
// or transmitted to another user
var myArrayAsString = JSON.stringify(pArray);

Later, you can retrieve the string and "rehydrate" it back into a useable javascript object like this:

// recreate the same pArray from the saved string
var pArray = JSON.parse(myArrayAsString);