javascript - 有人可以解释一下这个函数吗,因为我不确定使用索引的目的

标签 javascript html

<!DOCTYPE html> 
<html> 
<body>  

    <h1>JavaScript Task 3- Traffic Light Sequence </h1> 

  <img id="light" src="./assets/red.png" height="205" width="95">
  <button type="button" onclick="changeLights()">Change Lights</button>  
  <script> 
    var colours = ["./assets/red.png","./assets/red_and_amber.png", "./assets/green.png","./assets/amber.png" ];
    var index = 0;
    function changeLights() {
      index = index + 1;      
      if (index == colours.length) 
        index = 0;      
      var image = document.getElementById('light');     
      image.src = colours[index]; 
    } 
  </script>  
</body> 
</html>  

this code is to show a traffic light sequence. First red, then red and amber, then green, then back to amber, and then back to red. I'm unsure of what the function exactly does line by line.

最佳答案

索引是与颜色数组一起使用的数字。 例如:colours[0] 是数组中的第一个颜色; 然后索引+=1,现在索引==1; 第二次: colors[1] 是第二个,依此类推

关于javascript - 有人可以解释一下这个函数吗,因为我不确定使用索引的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40818947/

相关文章:

html - iframe 中的 SVG 存在奇怪的不一致问题

javascript - jquery 函数根据选择的选项显示/隐藏文本区域

javascript - Sails.js:如何使用模型关联填充数组

javascript - TinyMCE v4 关闭 blob

javascript - 使用 JQuery 通过迭代 ID 引用 DOM 元素

html - 在选项卡 Pane 中创建行和列的最佳方法

html - 来自动态 HTML 属性或类的 CSS 值以避免内联样式?

HTML:除了 'input type=text' 和 'textarea' 之外的选项?

javascript - 正则表达式不是运算符

javascript - 类型 'Subscription' 不可分配给类型 'Observable<Exercise[]>'