变量的作用域 如果变量是在 for 循环之前声明的,那么在 for 循环之后不应该访问它的值吗?



我在函数中声明了一些变量,它们的值在for循环中得到更新。在function结束时,我想看到其中一些变量的最终值。

在花了一整天的时间思考为什么我想要的没有发生之后,我在这里发布了这个函数,以获得一些见解。

在函数中,您可以看到两个alert s -第一个运行for的每次迭代,并给出变量的当前值。我不想要这个警告,但在这里插入它只是为了显示代码实际上做了我想要它在for loop中做的事情。

我想要的只是最后的alert ....但由于某种原因,它从未出现过!

在我的理解中,如果一个变量在函数的开头被声明,它的值可以一直访问到最后…如果这是正确的,为什么最后一个警报没有出现?

注意:这段代码是在MsWord生成的html上运行的,其中包含无数不必要的span标记,我需要在将内容用于文档目的之前删除这些标记。无法获得这些值是阻止我完成一个小工具的原因,我计划使用它来为一个项目转换大约400个MsWord页面!

function uponetag()
{
    var spank=document.getElementsByTagName('span'); //look at all span tags
    var spann=spank.length; //number of span tags on the page
    var yes=0;
    var no=0;
    for (i=0; i<=spann; i++)
        {
            var spancont=spank[i].innerHTML;
            //get the parent node
            var outer = spank[i].parentNode;
            outertag=outer.tagName.toLowerCase();
            //get the inner html of the parent node
            var outercont=outer.innerHTML;
            //create a string manually placing the opening and closing span tags around the current span content
            var compareit=("<span>"+spancont+"</span>");
            //compare the manual string to inner content of the parent node
            if (outercont===compareit)
            {
                //replace the inner html of the parent node with the current span content
                outer.innerHTML=spancont;
                yes=yes+1;
            }
            else
            {
                no=no+1;
            }
            alert ("Converted = "+yes+"nn Not converted = "+no); //this alert works
        }
    alert ("The page originally had "+spann+" span tags. n ON EXIT: Converted = "+yes+"nn Not converted = "+no);
    //THIS ALERT DOESN'T!!! WHY?????
}

我已经尝试了所有的变化(I =spannum, var1=....等等)建议在这里没有任何成功!实际上,在执行此操作时,我发现尽管原始页面中有49个span,但脚本在运行29次后(20次是和9次否)在firebug控制台中抛出错误。

代码读取超出数组长度,导致错误。

这就是为什么循环发出警报,而循环外的最终警报没有发出。

这个循环

for (i=0; i<=spann; i++)

包含i=spann,它比末尾大1。

我想你是想用

for(i=0;i<spann;i++)

是正确的

我还应该注意到Javascript没有块级变量。它具有function作用域的变量。在for循环块中声明var与在初始化当前function(称为提升)时声明var并将其设置在循环中相同。

for (i=0; i<=spann; i++)
//change it to :
for (i=0; i<spann; i++)

最新更新