gpt4 book ai didi

javascript - 如何将函数存储到数组中并在 javascript 中循环遍历每个函数

转载 作者:行者123 更新时间:2023-11-30 08:39:19 25 4
gpt4 key购买 nike

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);
}

在上面的代码中,我想将 drawscreen() 和 drawsscreen2() 函数存储到一个数组中,并循环以分别显示每个函数的点以进行操作。我该怎么做呢谁能帮我解决这个问题?

jsfiddle.net/karthikchandran/bn4kgov4 ..chk 这个演示,当我点击下一个按钮时,下一个函数简单地运行..我想要一个循环的所有函数,并在单击下一个按钮时一次迭代一个..

最佳答案

如何将函数存储到数组中:

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

如何遍历每个函数并运行它:

变体 1:

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

变体2(相同):

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

变体 3(相同,但 .forEach 不被 IE <= 8 版本支持):

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

变体 4(相同,但跨浏览器,需要 jQuery):

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

关于javascript - 如何将函数存储到数组中并在 javascript 中循环遍历每个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28186880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com