循环索引变量的Javascript成为全局范围的一部分? [英] Javascript for loop index variables become part of global scope?

查看:131
本文介绍了循环索引变量的Javascript成为全局范围的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我不知道 循环索引变量是如何得到范围的,但是当我的一个循环没有完成时我很惊讶,似乎是因为一个函数在循环中调用包含 i for 循环索引。

Perhaps I'm not aware of how for loop index variables get scoped, but I was very surprised when one of my loops didn't complete, seemingly because a function called from within a loop contained an i for its for loop index as well.

这是我用来展示这种行为的一个小脚本:

Here's a little script I put together to demonstrate this behavior:

var loopOne = function(test) {
    for(i = 0; i < test.length; i++)
        console.log(getMask(test));
};

var getMask = function(pass) {      
    var s = "";
    for (i = 0; i < pass.length; i++) {
        s = s + "*";
    }
    return s;      
};

loopOne('hello');

如果我在Chrome中运行此操作并查看控制台日志,我应该看到 ***** 五次。但是,我只看过一次。经过进一步检查,如果我在Chrome javascript控制台中输入 i ,它将输出6( ='hello'.length + 1 )。这让我认为 i 已成为全球范围的一部分,并且不限于的范围需要它的循环。

If I run this in Chrome and look at the console log, I should see ***** five times. However, I only see it once. Upon further inspection, if I type i in the Chrome javascript console, it will output 6 ( = 'hello'.length + 1). This makes me think that i has become a part of the global scope and is not limited to the scope of the for loop for which it was needed.

这是正确的吗?如果是这样,在javascript中为 c>循环定义的索引变量有什么更好的做法?

Is this correct? If so, what's a better practice for defining the index variable of a for loop in javascript?

推荐答案

在Javascript中,变量的作用域是 var 关键字。使用 var 声明变量时,变量的范围限定为当前函数。在不使用 var 关键字的情况下分配给变量时,假设您正在讨论相同或更高范围内已定义的变量。如果没有找到,则变量在最高范围内创建。

In Javascript, variables are scoped with the var keyword. When declaring variables with var, the variable is scoped to the current function. When assigning to a variable without using the var keyword, it is assumed you're talking about an already defined variable in the same or a higher scope. If none is found, the variable is created in the highest scope.

底线:使用 var 。

这篇关于循环索引变量的Javascript成为全局范围的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆