简体   繁体   English

如果我多次声明相同的变量,我会有任何问题吗?

[英]Will I have any problems if I declare the same variable multiple times?

So lets say I have some code: 所以我想说我有一些代码:

//Javascript
var elements = [];
function addNumbah1(){
    var i = 1;
    elements.push(i);
}
function addNumbah2(){
    var i = 2;
    elements.push(i);
}

And that goes on up to addNumbah999(), is it bad form to declare the i variable every time? 这继续addNumbah999(),每次声明i变量是不好的形式? Will that break anything? 会破坏什么吗? Should I do: 我应该这样做:

//Javascript
var elements = [];
var i
function addNumbah1(){
    i = 1;
    elements.push(i);
}
function addNumbah2(){
    i = 2;
    elements.push(i);
}

Short answer: NO , JS hoists all variable declarations to the top of the scope, regardless of how many times you've declared them: 简短回答: ,JS将所有变量声明提升到范围的顶部,无论您声明它们多少次:

var i = 0
for (var i=0;i<10;i++)
{
    var j = i%2;//declared 10 times, on each iteration
}

Will be translated to 将被翻译成

var i, j; //i is undefined at this point in the code.
for (i = 0;i<10;i++)
{
    j = i%2;//declared 10 times, on each iteration
}

In your first example, you're declaring i as a variable in a function's scope, which is what you must do to avoid cluttering the global scope. 在第一个示例中,您将i声明为函数范围中的变量,这是您必须要做的,以避免混乱全局范围。 The memory these variables use is allocated when the function is called, and deallocated when the function returns (roughly, closures form an exception, but that would take us to far). 这些变量使用的内存在调用函数时分配,并在函数返回时释放(粗略地说, 闭包形成一个异常,但这会把我们带到远处)。 Consider this: 考虑一下:

var i = 10;
function someF()
{
    var i = 1;
    alert(i);
}
someF();//alerts 1 <-- value of i, local to someF
alert(i);//10, global i is unchanged

But if you were to omit the var : 但是如果你要省略var

function someF()
{
    i = 1;
    alert(i);
}

You'll see that 1 is alerted twice. 你会看到1被警告两次。 If JS can't find a variable declaration in the current scope, it will look in the higher scopes until a var is found. 如果JS在当前作用域中找不到变量声明,它将在更高的作用域中查找,直到找到var。 If no variable is found, JS will create one for you in the highest scope (global). 如果没有找到变量,JS将在最高范围(全局)中为您创建一个变量。 Check my answer here on how implied globals work for a more detailed example, or read the MDN pages , especially the section on Name conflicts 在这里查看我的答案 ,了解隐含的全局变量如何用于更详细的示例,或者阅读MDN页面 ,尤其是关于名称冲突的部分

Lastly, I'd like to add that globals, especially implied globals, are evil . 最后,我想补充一点,全局变量,特别是隐含的全局变量,都是邪恶的 Also know that the ECMA6 standard is clearly moving away from global variables and introduces support for true block-scopes. 还要知道ECMA6标准明显偏离了全局变量,并引入了对真正的块范围的支持。 As you can see here 正如你在这里看到的那样
Oh, and if you want to check if a function uses implied globals: 'use strict'; 哦,如果你想检查函数是否使用隐含的全局变量: 'use strict'; is a great thing: 是一件好事:

(function()
{
    'use strict';
    var localVar = 123;//ok
    impliedGlobal = 123;//TypeError!
}());

As you can see, implied globals are not allowed. 如您所见,不允许使用隐含的全局变量。 See MDN on strict mode for the full explanation 有关完整说明,请参阅严格模式下的MDN

The second form, with global i might actually be a bit slower because it's defined in a higher scope, and variables defined in a higher scope take longer to resolve. 第二种形式,全局i可能实际上有点慢,因为它在更高的范围内定义,而在更高范围内定义的变量需要更长的时间来解决。

Aside from any performance considerations just stick with common guidelines unless performance is really an issue. 除了性能因素之外,只需坚持使用通用指南,除非性能确实存在问题。 In this case: scope your variables as narrowly as possible . 在这种情况下: 尽可能缩小变量的范围

I would strongly advise you to use the first form. 我强烈建议你使用第一个表格。

The first way you did it is fine. 你做的第一种方式很好。 Each instance of i would have no knowledge of the other i in the other functions. i的每个实例都不会知道其他函数中的其他i。

You should read this tutorial on global versus local variables 您应该阅读有关全局变量和局部变量的本教程

Also, could I suggest an optimization. 另外,我可以建议进行优化。 Why can't you just do the following to cover any number (instead of separate functions for each number)? 为什么不能只执行以下操作来覆盖任何数字(而不是每个数字的单独功能)?

var elements = [];
function addNumbah(number){
    elements.push(number);
}

You can declare a variable multiple times..In your code you are declaring Variable i in different scopes here: 你可以多次声明一个变量..在你的代码中,你在这里声明了不同范围的变量i:

   //Here you are declaring variable i local to addNumbah1,2 functions 
   var elements = [];
   function addNumbah1(){
       var i = 1; 
       elements.push(i);
   }
   function addNumbah2(){
       var i = 2; 
       elements.push(i);
   } 


   //Here v /variable i has been declared globally
   var elements = [];
   var i
   function addNumbah1(){
       i = 1;   
       elements.push(i);
   }
   function addNumbah2(){
       i = 2;  
       elements.push(i);
   }

Note that although you can declare a variable multiple times but generally its not a good programming practice as it may cause bugs/problems in your application 请注意,尽管您可以多次声明变量但通常不是一个好的编程习惯,因为它可能会导致应用程序中出现错误/问题

可以在不同的函数中声明具有相同名称的变量。

Variables declared inside a function only exist in the scope of that function, so having the same variable name across different functions will not break anything. 在函数内声明的变量只存在于该函数的范围内,因此在不同函数中具有相同的变量名称不会破坏任何内容。

In fact, it is good form to keep variables in as small of a scope as possible! 实际上,将变量保持在尽可能小的范围内是一种很好的形式! Global variables can be difficult to manage and can create really bad bugs, especially if one function isn't done using the variable when another function tries to access it. 全局变量可能难以管理,并且可能会创建非常糟糕的错误,尤其是当另一个函数试图访问它时,如果没有使用该变量完成一个函数。

Specifically for simple variables, declaring 特别针对简单变量,声明

var i = 0;

every time is perfectly fine. 每次都很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用同一个createElement变量多次使用appendChild - How can I use appendChild multiple times with the same createElement variable 如果我在同一个视图上多次使用它,如何为同一个 ng-include 提供不同的行为? - How to provide different behavior to the same ng-include if I have it multiple times on the same view? 在同一模块中多次声明AngularJS服务 - Declare AngularJS service multiple times in the same module 我是否总是必须在angular2中声明变量才能获得更改? - Do I always have to declare a variable in angular2 to get changes? 我应该如何声明一个具有 setInterval 值的变量? - How should I declare a variable that will have the value of setInterval? 我可以在一条路由中多次使用npm request并将结果显示在同一页面上吗? - Can I use npm request multiple times in one route and have the results display on the same page? 我必须添加什么才能使同一段落打印 3 次? - what do I have to add to have the same paragraph to print 3 times? 在js中我和css一样吗? - any same way in js as I have in css? 无论如何,当我在页面上有多个Like按钮时,是否会阻止多次加载相同的JS / CSS文件? - Is there anyway to prevent the same JS/CSS file from being loaded multiple times when I have multiple Like buttons on a page? 如果我在“用户受限”页面上使用Google Analytics(分析),会不会有任何问题 - Will Google Analytics have any problems if I use it on User Restricted pages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM