Notice that i
is a variable that changes in this scope. When console.log(x[i]);
is run i
already received another value because it was within loop
.
In ES6 (the new version of JavaScript) you can use let
and your problem disappears. The let
creates a variable in the scope of this block of code and therefore does not interfere with the global variable.
Take a look here:
for (let i = 0; i < 10; i++){
setTimeout(function(){ console.log(i); }, 500);
// dá sempre o numero certo, apesar de ser meio segundo depois
}
example online: link
But in your example, using the version that the old browsers use, you have to pass this i
to a function so that it is saved with the value it had at the moment. For example:
function handler(index){
return function(){
console.log(x[index]);
}
}
and within for
do so:
for(i=0;i<y.length;i++){
if(y[i].childElementCount > 0){
y[i].addEventListener('click', handler(i));
}
}
jsFiddle: link
or even closer to your code:
for (i = 0; i < y.length; i++) {
if (y[i].childElementCount > 0) {
(function(ind) {
y[ind].onclick = function() {
console.log(x[ind], ind, i);
}
})(i);
}
}
example: link
You have an explanation of this problem and workarounds in this other question , too.