循环内的Javascript变量声明 [英] Javascript variable declaration within loop

查看:59
本文介绍了循环内的Javascript变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个强迫性的习惯,但我认为可能完全没有必要.使用如下代码:

I have a habit that I am borderline compulsive about, but I think may be completely unnecessary. With code like:

function abc(){
  var a,b;
  for(var i=0;i<10;i++){
    a=document.getElementsByTagName('LI').item(i).width;
    b=document.getElementsByTagName('DIV').item(i).width;
    // now do something with a and b
   }
   return;
}

我很强迫在循环之前声明变量,而不是:

I am compulsive about declaring the variable before the loop as opposed to:

function abc(){
  for(var i=0;i<10;i++){
   var a=document.getElementsByTagName('LI').item(i).width;
   var b=document.getElementsByTagName('DIV').item(i).width;
    // now do something with a and b
   }
   return;
}

请注意,在第二个代码块中,每次循环迭代时,我都使用 var 定义变量.我认为第一个是可读性的最佳实践,等等.但是有时候我只是在破解某些东西,而无需遵循最佳实践.

Notice that in the second code block, I define the variable with var each time the loop iterates. I imagine the first is best practice for readability, etc. But sometimes I'm just hacking something and don't need to follow best practice.

我的问题是:

是否有任何原因定义将在循环内使用 var 关键字重新定义的变量?

Is there any reason not to define a variable that will be getting redefined using the var keyword inside a loop?

推荐答案

由于Java语言中的变量提升,在函数顶部或内部的 var 之间在执行方面没有技术上的区别 for 循环.如果您只关心这些,那么您可以选择其中任何一种方式.

Because of variable hoisting in Javascript, there is no technical difference in execution between the var being at the top of the function or inside the for loop. If that is all you care about, then you can do it either way.

只是刷新内存,Javascript提升意味着将解析第二个代码块之类的代码,然后像第一个代码块一样执行.函数中的所有 var 声明在执行前都会自动移至函数作用域的顶部.这些变量的分配将保留在代码中它们的位置-仅移动变量的声明.

Just to refresh memory, Javascript hoisting means that code like your second code block is parsed and then execute just like your first code block. All var declarations within a function are automatically moved to the top of the function scope before execution. Assignments to those variables are kept where they are located in the code - just the declaration of the variable is moved.

因此,不同之处在于您要如何编码外观.将 var 定义放入 for 循环中时,它会使代码看起来像为 for 的每次迭代重新创建变量.循环,即使事实并非如此.在循环的每次迭代中都会为它们分配一个值,但是不会创建新变量.如果您使用 let 而不是 var 会是这种情况,因为 let 具有块作用域,而 var 仅具有块作用域功能范围.

So, the difference is more about how you want to code to look. When you put the var definitions inside the for loop, it makes the code look like the variables are being created anew for each iteration of the for loop, even though that is not the case. They are being assigned a value each iteration of the loop, but a new variable is not created. That would be the case if you used let instead of var since let has a block scope whereas var only has function scope.

通常,最好仅将代码放入实际上需要放入循环的循环中.尽管 var 是在循环内还是循环外实际上并没有改变任何执行内容,但这只是一种良好做法,而在循环内或循环外的其他代码可能会有所作为.

In general, it is a good practice to only put code inside a loop that actually needs to be inside the loop. While it doesn't actually change anything in the execution whether the var is inside or outside the loop, it is just part of a good practice whereas other code being inside or outside the loop could make a difference.

对于您而言,我认为这是一种更好的做法:

In your case, I think this would be a better practice:

function abc(){
  var liTags = document.getElementsByTagName('LI');
  var divTags = document.getElementsByTagName('DIV');
  var len = Math.min(liTags.length, divTags.length);
  var a,b;

  for(var i = 0; i < len; i++){
    a = liTags[i].width;
    b = divTags[i].width;

    // now do something with a and b

   }

   return;
}

在这里,您已从循环中删除了对 document.getElementsByTagName()的两个调用,这将大大提高性能.

Here, you've removed the two calls to document.getElementsByTagName() from the loop which will make a HUGE performance difference.

2017年更新. Javascript版本ES6现在支持 const let 来声明变量.它们是块作用域的,而不是像 var 这样的函数作用域的,因此,如果在 for 循环块中声明它们之一,则将为每个变量创建一个新的独立变量调用 for 循环.虽然这不会对您显示的代码类型产生任何显着的执行差异,但是如果您在循环内有异步代码引用了您声明的变量,则可能会有所不同.如果在循环体内使用 const let ,则每个异步调用将获得其自己的变量副本,有时可能非常方便.

Update in 2017. Javascript version ES6, now supports both const and let for declaring variables. They are block scoped, not function scoped like var, so if you declare one of them inside a for loop block, then there will be a new and separate variable created for each invocation of the for loop. While that wouldn't make any significant execution difference in the type of code you showed, it can make a difference if you had asynchronous code inside the loop that references the variable you were declaring. In the case of const or let used within the loop body, each asynchronous call would get its own separate copy of the variable which can sometimes be very handy.

  for(var i = 0; i < len; i++){
      let a = liTags[i].width;
      let b = divTags[i].width;
      
      $.get(someUrl).then(function(data) {
          // each call to $.get() here in the loop has it's own a and b
          // variables to use here, which would not be the case with var
      });

   }

这篇关于循环内的Javascript变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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