Reputation: 3713
I have two functions, let's say:
getCustomers() - get customers list getCustomerDetials() - get details of each customer
I run getCustomers()
and that function runs within itself the getCustomerDetails()
…
Obviously, I need to list all customers and its details.
So, here goes the process.
getCustomers()
loads a list of all customer ids and loops through each customer id :
for(i = 0; i < array_count; i++);
firing the getCustomerDetails(id)
on each of the customers found.
getCustomerDetails
then runs its own internal loop:
for(i = 0; i < array_count; i++);
to loop through each detail.
The problem: I had two identical for loops running both from the parent function and the function running internally.
Basically, it seems that my innter for loop "i" variable is updating the parent for loop "i" variable and it never finishes!
I changed the internal function's loop "i" variable into i2 and all was well again.
Sorry for the long explanation but i just wanted to make it clear that this is normal and expected outcome? Or there's something wrong w/ my code?
I've dealt with a few languages (I'm a seasoned PHP and AS2 programmer) and I never encountered this colision before… I'm not that good in JS though so.
Upvotes: 0
Views: 71
Reputation: 385104
I THOUGHT variables declared inside functions stay local?
They do; the problem is that you didn't declare your variable inside the function.
Use the var
keyword to declare variables:
for (var i = 0; i < array_count; i++)
Without this keyword, you are using a global variable.
This should be covered in your JavaScript book. Which one are you using?
Upvotes: 7