Im trying to learn javascript by tracing through some code at the moment, I was wondering if someone could explain what is happening in this snippet of code (this snippet is just part of a function hence no closing brace):
document.addEventListener("keydown",function(e){
for(i=0;i < keys.length; i++) {
if(e.keyCode == keys[i]){
var tri = document.getElementById("foo").childNodes[i];
if(i==0){
var tri = document.getElementById("foo").childNodes[1];
}
if(i==1){
var tri = document.getElementById("foo").childNodes[3];
}
if(i > 1) {
var tri = document.getElementById("foo").childNodes[(i*2)+1];
}
The part im confused about most in this is the childNodes[] and the if(i) statements?
Note that
var tri = document.getElementById("foo").childNodes[i];is a useless line, becauseicannot be negative, one of the next three if statements will always succeed andtriwill be overwritten.Also note that when
i = 0,(i*2)+1 = 1and wheni = 1,(i*2)+1 = 3, so those other two if statements are useless as well because the third covers all cases and doesn’t need to even be in an if clause. The above code is 100% equivalent to:Since
iis the variable used to iterate through the array calledkeys, and the node selected depends oni.keysmust be an array with an unusual purpose. It is an array of keyCodes, where the position of the keyCode in the array determines which node should be selected and stored intriwhen that key is pressed.