I have a function which loops an array… whilst it works it seems to change the value of the information being sent from “begin” function to “process” function, but i don’t know why… I’m sure i made a silly mistake but I cannot see the mistake =/
This is my function:
var array_data = data[9]; //global array to use
console.log(array_data); //debug
function process(i){
alert('Number is '+i); // shows the value "7" (should show value "1")
}
function begin(){
var count = 0;
for(i in array_data){
if(parseInt(array_data[i][9])){ //if true
var result = create_layout(i); //function to make the layout
alert('Number is '+i); //shows the value "1" (this is correct so far)
document.getElementById('result'+count).innerHTML = result;
document.getElementById('result'+count).onclick = function() { process(i); };
count++;
}
}
window.onload = function() {
begin();
};
Below is my array for (array_data) from the console log:
1: Array[10]
0: "Car One"
1: "1"
2: "3"
3: "d2.jpg"
4: "1"
5: "1"
6: "200"
7: "85"
8: "5000"
9: "1"
length: 10
7: Array[10]
0: "Car Two"
1: "1"
2: "1"
3: "e2.jpg"
4: "1"
5: "0"
6: "500"
7: "50"
8: "3000"
9: "0"
length: 10
So I’m wondering why might it is changing the value of “i” when it reaches the process function ?
By the time the
onclickfunction actually gets called, the value ofiwill have changed because of the loop it’s in. You should “anchor” its value. The easiest way to do it is like this:This will ensure that the value of
iwill not change within that closure (unless you change it yourself)