I’m trying to count the elements inside an array, and the number has to be updated each time elements are added. I’m trying to do this by using the following function:
function counter() {
for(var i = 0; i < elements.length; i++) {
counter = i;
}
alert("counter has counted");
}
but it only works the first time! The second time the function is called it doesn’t work anymore and the alert is not even showing up, so I guess the process gets interrupted in the for loop. Anyone knows the reason?
You shouldn’t use the same name (
counter) for the variable that stores the count and for your function.The line
counter = i;overwrites the reference to your function. The next time you try to callcounter()it won’t work becausecounteris no longer a function.Try this instead: