gpt4 book ai didi

javascript - 在 javascript 中使用数组作为函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:25:55 24 4
gpt4 key购买 nike

我正在尝试创建一个程序,该程序使用一组函数来循环执行顺序。我已经包含了下面的程序,有人可以建议我做错了什么。我在 HTML 上创建了一组交通灯,我正在尝试编写一些 javascript 来更改单击按钮时显示的灯。我创建了一组函数来确定我希望灯光出现的顺序。我还编写了将显示每盏灯的函数。我是 javascript 的新手,如有任何帮助,我们将不胜感激。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Task three</title>
<link href="Task 3-CSS.css" rel="stylesheet" type="text/css" />
<script src="Task3-Java.js"></script>
</head>

<body>

<div id="control_panel">
<button onclick="change_light">Change Light</button>
</div>

<div id="traffic_light">
<div id="red_light" class="light"></div>
<div id="amber_light" class="light"></div>
<div id="green_light" class="light"></div>
</div>
</body>
</html>

var light_array=[red,red_amber,green,amber];
var light_index = 0;

function no_light(){
document.getElementById('red_light').style.backgroundColor = "black";
document.getElementById('amber_light').style.backgroundColor = "black";
document.getElementById('green_light').style.backgroundColor = "black";
}

function red(){
no_light();
document.getElementById('red_light').style.backgroundColor="red";
}

function red_amber(){
no_light();
document.getElementById('red_light').style.backgroundColor="red";
document.getElementById('amber_light').style.backgroundColor="orange";
}

function green(){
no_light();
document.getElementById('green_light').style.backgroundColor="green";
}

function amber(){
no_light();
document.getElementById('amber_light').style.backgroundColor="orange";
}

function change_light(){
light_array[light_index](red,red_amber,green,amber);
light_index++;
if (light_index > 3){light_index = 0;}

}
change_light();

最佳答案

您正在调用 函数并将结果存储在数组中。你应该只引用它们(没有 ()):

var light_array=[red,red_amber,green,amber];

然后在您想调用它们时调用它们(例如,在 change_light 中):

light_array[light_index]();
// ---------------------^

顺便说一句,更新 light_index 的代码不正确,您应该在 if 之前递增:

function change_light(){
light_array[light_index]();
light_index++; // <== Moved this up
if (light_index > 3){light_index = 0;}
}

...但是有一个方便的技巧可以将它组合成一个表达式:

function change_light(){
light_array[light_index]();
light_index = (light_index + 1) % light_array.length;
}

这会为您处理回绕。另请注意我是如何使用 light_array.length 而不是硬编码数字的,因此如果您在数组中添加/删除条目,代码仍然有效。

关于javascript - 在 javascript 中使用数组作为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43473728/

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