Why the value inside the loop and using the [i] is undefined?
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 =开发者_JS百科 0;
for (i=0;i<=4;i++)
{
var linking= links[i];
}
jetpack.notifications.show(" "+ linking);
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.
精彩评论