I have this small source of code
for (i = 0; i < elements.length; i++) {
console.log(i);
(function (i) {
if (elements[i]["id"] == id) {
index = i;
console.log(i);
}
})(i);
}
console.log(index);
I want to find an array's element index where sub element "id" = id; but it returns sometimes 0 simetimes 1. This code is inside a function that is inside a class. and I call the same function twice but with different parameters outside of the class, so first it must show 0 and than 1, but sometimes it shows 1 and than 0. so can you help me? I tried this method too but it doesn't work.
var i = 0;
while (i < elements.length) {
console.log(elements[i]["id"]);
if (elements[i]["id"] == id) {
index = i;
break;
} else if (elements[i]["id"] != id) {
i++;
}
}
console.log(index);
Here is my test page, If you open it with Chrome (sometimes it happens but in Firefox it happens mostly) you will see that sometimes small image appears but sometimes it disapears when you press the button. You can also see the console output in "inspect elements -> console"
EDIT
I changed my code for better debug like this (as Lando suggested) :
for (i in elements){
console.log("comparing elements['"+ i +"']['id']: "+ elements[i]["id"] +" with id:' "+ id + "'");
if(elements[i]["id"] == id){
index = i;
}
}
console.log(index);
and got console ouput:
comparing elements['0']['id']: id2 with id:' id1' Slideshow.js:140
comparing elements['1']['id']: id1 with id:' id1' Slideshow.js:140
1 Slideshow.js:147
comparing elements['0']['id']: id2 with id:' id2' Slideshow.js:140
comparing elements['1']['id']: id1 with id:' id2' Slideshow.js:140
0
When it should be:
comparing elements['0']['id']: id1 with id:' id1' Slideshow.js:140
comparing elements['1']['id']: id2 with id:' id1' Slideshow.js:140
0 Slideshow.js:147
comparing elements['0']['id']: id1 with id:' id2' Slideshow.js:140
comparing elements['1']['id']: id2 with id:' id2' Slideshow.js:140
1
EDIT 2
After seeing the output it turns out that objects in array "elements" change places, elements[0]["id"] becames "id2" where it should be "id1" I can't still difinetly say why is this happening or what to do to fix it. so please if you have any ideas share it.