Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue in Loop calling

I am working in JavaScript. I have an issue with loop calling.
My code is :

Here is My Array

picArray = []; // Have tried with this too var picArray = new Array();

Here is My onClick function:

handler:function(){
    for(var i = 1; i<picArray.length; i++) {
        alert(picArray[i]);
    }
}

This is my loop to print the values from an array. And my Array is:

var imgSource = document.getElementById(hellow).src;
picArray[hellow] = imgSource;

This array is getting data on a condition. Handler function is called on click of a Button called Upload. The problem is When I press the Upload button it prints the correct values and remain pressed and print the values again. Is there any mistake in my code which compelling the loop to print values for 2 times?
Or anything else is doing this?

like image 314
Burhan Mughal Avatar asked Apr 13 '26 09:04

Burhan Mughal


2 Answers

I think you should consider using a closure function on clicking the button, for retaining the scope of the outer context. My supposition is that the root of the problem relays on the fact, that when you are entering the loop condition, you are getting the final value only when the loop has finished.

This problem can be solved by creating a function and calling it on each iteration of the loop, while passing i; calling the function will form a brand new execution context where the value of i is retained and can be used in any way within that context, including within the returned function.

Because you didn't post the rest of the code, i only suppose that's the problem. For solving this problem, here is the code i would use on this context:

function handler(n) {
    return function() {
        alert( 'You clicked on: ' + n );
    };
}

for (var i = 0; i < picArray.length; ++i) {
    picArray[i].onclick = handler(i);
}

...or another more elegant way:

for (var i = 0; i < picArray.length; ++i) {
    picArray[i].onclick = (function(n) {
        return function() {
            alert( 'You clicked on: ' + n );
        };
    })(i);
}
like image 160
Endre Simo Avatar answered Apr 14 '26 22:04

Endre Simo


It looks like an associative array (since hellow is both an element ID and array key) but you are accessing it like an indexed array.

So you should do this instead:

for (var key in picArray) {
    alert(picArray[key]);
}
like image 33
laurent Avatar answered Apr 14 '26 22:04

laurent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!