views:

43

answers:

1

using Mozilla jetpack , when i do the following code .. i get that linking is undefined !!! why ? or how to fix it ?

var links = doc.querySelectorAll('#courses_menu > ul > li > a'); 
var linkz=links[1].href.split("?");

var i = 0;
for (i=0;i<=4;i++)
{
   var linking= links[i]; 
}
jetpack.notifications.show(" "+ linking); 
A: 

Because it goes out of scope when the loop ends.

So you should have

var linking;
for (i=0;i<=4;i++)
{
   linking= links[i]; 
}

But furthermore, what are you trying to do here? You overwrite linking four times. Do you want to display all of the links? If so, you can concatenate them like:

var linking = "";
for (i=0;i<=4;i++)
{
   linking = linking + links[i] + " "; 
}

Edit: the commenters are right; I did forget that there is no block scoping in Javascript. Did this fix your code? I can't imagine that it did. The only other thing that I can think of is that links[4] is undefined, and then you would be assigning undefined to linking.

Anyway, I can't delete this because it's been accepted, but if anyone else comes up with a more useful answer, feel free to unaccept this one.

danben
Thank youuu .. You are Right .. i can't believe this didn't cross my mind !
msheshtawy
Not to my knowledge, or my spontaneous tests. Javascript maintins function scope, not block scope. Any variable declared inside a for loop will be accessible for the rest of the function until the function returns.
seanmonstar
@seanmonster: If you declare it in or of the for loop (eg, `for(var i...`), it only exists in the for loop.
Anonymous
Um, no. Javascript only uses function scope. Try it: http://jsbin.com/uxaci3/edit
seanmonstar