繁体   English   中英

有人可以向我解释这段代码吗

[英]Can someone explain this piece of code to me

这段代码中的字符串是什么意思,它是交通灯脚本的一部分,我不知道每一行是做什么的。

var index = 0;
var variableLen = variable.length;

function nextvariableClick() {
    index++;

    if (index == variableLen) 
        index = 0;

    var image = document.getElementById('starting_light');
    image.src = variable[index];

variable似乎是一个数组,用于存储对图像的引用(URI 或路径),该数组被馈送到图像元素的src属性<img> 脚本简单执行以下逻辑:

  • 当函数被触发时,它会将index增加 1
  • 如果索引等于图像的数量,则将其返回到 0(基本上“循环”通过数组
  • 您通过索引index将图像源设置为variable数组的第 n 个元素

一个聪明的猜测是这是一个图像循环功能。 nextvariableClick被调用时,它会按照图像在variable数组中出现的顺序循环遍历图像列表。

由于脚本如此简单,查看其功能的最佳方法是构建一个函数式代码片段:

 // Define dummy image references var variable = [ 'https://placehold.it/500x300/e41a1c/ffffff', 'https://placehold.it/500x300/377eb8/ffffff', 'https://placehold.it/500x300/4daf4a/ffffff', 'https://placehold.it/500x300/984ea3/ffffff', 'https://placehold.it/500x300/ff7f00/ffffff' ]; /* Start of code you have provided */ var index = 0; var variableLen = variable.length; function nextvariableClick() { index++; if (index == variableLen) index = 0; var image = document.getElementById('starting_light'); image.src = variable[index]; } /* End of code you have provided */ // We execute the function to start initialise it, and set a starting image nextvariableClick(); window.setInterval(nextvariableClick, 1000);
 <p>The function is called at runtime, and called every 1s. You should see cycling of image sources.</p> <img id="starting_light" src="" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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