var list=["https://stackoverflow.com/questions/37702877/Red.jpg","Amber.jpg","Green.jpg","AmberLast.jpg"];
this is an array of names of image sources.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
var index = 0;
this a variable, it’s called index, and has the value of 0 because you can target an element of an array (e.g Amber.jpg) using it’s index. An array’s index by default starts at 0 (zero based), so in the ‘list’ array above, the index of 0 (list[0]) will return “https://stackoverflow.com/questions/37702877/Red.jpg”.
function changeLights() {
var image = document.getElementById("https://stackoverflow.com/questions/37702877/Red.jpg");
var display = document.getElementById('display');
index = (index + 1) % 4;
image.src = list[index];
display.innerHTML = list[index];
}
This function selects the <img>
tag with the ID of “https://stackoverflow.com/questions/37702877/Red.jpg”, and then sets it’s src= to be index + 1 (= 1)
, and then sets the inner HTML of the element with an ID of display to be Amber.jpg (list[1]).
The correct way to ‘change lights’ would instead be:
var list=["https://stackoverflow.com/questions/37702877/Red.jpg","Amber.jpg","Green.jpg","AmberLast.jpg"];
var index = 0;
function changeLights() {
var max = list.length - 1;
var next = index += 1;
if(next > max) {
next = 0; //start back at beginning
index = 0;
}
var image = document.getElementById('IDOFIMAGETAG'); //replace will correct ID of <img>
image.src = list[next];
}
3
solved Could you help me Explain what this means?