Hi,
Yes, you should use a `var` statement -- specifically, two of them.
With your functions as quoted, you're falling prey to the Horror of
Implicit Globals[1], meaning that both your `A` and `B` functions are
using the *same* variable (a global variable), and so of course `B` is
interfering with `A`'s loop.
Corrected:
function B()
{
var i; // <== The new bit
for(i=0;i<array_b_length;i++)
{
...
}
}
function A()
{
var i; // <== The new bit
for(i=0;i<array_a.length;i++)
{
B()
...
}
}
Now `A` and `B` each have their own, independent, local `i` variable.
Also worth reading up on the `var` keyword[2], which is sometimes
misunderstood.
[1] http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html
[2] http://blog.niftysnippets.org/2008/03/poor-misunderstood-var.html
HTH,
--
T.J. Crowder
Independent Software Engineer
tj / crowder software / com
www / crowder software / com
On Jan 19, 1:31 pm, Ran Berenfeld <[email protected]> wrote:
> Hello all
>
> sorry for this stupid question, but all these talks about the "*this"
> pointer and the variable
> scope in js got me confused.
> support I have 2 functions, one calling the other inside array iteration.
> can they both
> use the same local variable for array index ?
> should I use a "var" statement ?
>
> for example :
>
> function B()
> {
> for(i=0;i<array_b_length;i++)
> {
> ...
> }
>
> }
>
> function A()
> {
> for(i=0;i<array_a.length;i++)
> {
> B()
> ...
> }
>
> }
>
> Thanks
> Ran
--
You received this message because you are subscribed to the Google Groups
"Prototype & script.aculo.us" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/prototype-scriptaculous?hl=en.