Programing

JavaScript의 "for-in"루프에 "var"또는 "var"없음?

lottogame 2020. 8. 26. 08:21
반응형

JavaScript의 "for-in"루프에 "var"또는 "var"없음?


for-inJavaScript 에서 루프 를 작성하는 올바른 방법은 무엇입니까 ? 브라우저는 내가 여기에서 보여주는 두 가지 접근 방식 중 하나에 대해 불만을 제기하지 않습니다. 첫째, 반복 변수 x가 명시 적으로 선언 되는 다음 접근 방식이 있습니다 .

for (var x in set) {
    ...
}

그리고 대안으로 더 자연스럽게 읽지 만 나에게 맞지 않는이 접근 방식 :

for (x in set) {
    ...
}

를 사용 var하면 변수의 범위가 줄어 듭니다. 그렇지 않으면 변수가 var문을 검색하는 가장 가까운 클로저를 찾습니다 . 를 찾을 수 없으면 var전역입니다 (엄격 모드에있는 using strict경우 전역 변수에서 오류가 발생 함). 이로 인해 다음과 같은 문제가 발생할 수 있습니다.

function f (){
    for (i=0; i<5; i++);
}
var i = 2;
f ();
alert (i); //i == 5. i should be 2

당신이 작성하는 경우 var i루프에 대한 경고 쇼에 2.

자바 스크립트 범위 지정 및 호이 스팅


첫 번째 버전 :

for (var x in set) {
    ...
}

라는 지역 변수를 선언합니다 x. 두 번째 버전 :

for (x in set) {
    ...
}

하지 않습니다.

경우 x(당신이 가지고 즉, 이미 지역 변수 var x;또는 var x = ...;어딘가에 이전 현재 범위 (즉, 현재 함수)) 그들은 동등 할 것이다. x가 아직 지역 변수가 아닌 경우 두 번째를 사용하면 암시 적으로 전역 변수를 선언합니다 x. 이 코드를 고려하십시오.

var obj1 = {hey: 10, there: 15};
var obj2 = {heli: 99, copter: 10};
function loop1() {
    for (x in obj1) alert(x);
}
function loop2() {
    for (x in obj2) {
        loop1(); 
        alert(x);
    }
}
loop2();

당신이 경고에이를 기대할 수 hey, there, heli, hey, there, copter,하지만 이후 x하나가 알려드립니다 동일 hey, there, there, hey, there, there. 당신은 그것을 원하지 않습니다! 루프 var x에서 사용하십시오 for.

To top it all off: if the for loop is in the global scope (i.e. not in a function), then the local scope (the scope x is declared in if you use var x) is the same as the global scope (the scope x is implicitly declared in if you use x without a var), so the two versions will be identical.


You really should declare local variables with var, always.

You also should not use "for ... in" loops unless you're absolutely sure that that's what you want to do. For iterating through real arrays (which is pretty common), you should always use a loop with a numeric index:

for (var i = 0; i < array.length; ++i) {
  var element = array[i];
  // ...
}

Iterating through a plain array with "for ... in" can have unexpected consequences, because your loop may pick up attributes of the array besides the numerically indexed ones.

edit — here in 2015 it's also fine to use .forEach() to iterate through an array:

array.forEach(function(arrayElement, index, array) {
  // first parameter is an element of the array
  // second parameter is the index of the element in the array
  // third parameter is the array itself
  ...
});

The .forEach() method is present on the Array prototype from IE9 forward.


Actually, if you dislike declaration within for heading, you can do:

var x;
for (x in set) {
    ...
}

As mentioned in other answers to this question, not using var at all produces unnecessary side-effects like assigning a global property.


Use the one where you declare the loop variable with var. Implicitly declared variables have a different scope that's probably not what you intended.


for(var i = 0; ...)

is a commonly seen pattern but it's different from

for(int i; ...)

in C++ in that that the variable isn't scoped to the for block. In fact, the var gets hoisted to the top of the enclosing scope (function) so a local i will be effectively available both before the for loop (after the beginning of the current scope/function) and after it.

In other words, doing:

(function(){ //beginning of your current scope;
 //...
 for(var i in obj) { ... };
})();

is the same as:

(function(){ //beginning of your current scope;
 var i;
 //...
 for(i in obj) { ... };
})();

ES6 has the let keyword (instead of var) to limit the scope to the for block.

Of course, you SHOULD be using local variables (ones declared with either var or let or const (in ES6)) rather than implicit globals.

for(i=0; ...) or for(i in ...) will fail if you use "use strict"; (as you should) and i isn't declared.


Using var is the cleanest way, but both work as described here: https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in

Basically, by using var you ensure that you create a new variable. Otherwise you might accidentally use a previously defined variable.


I think var is good for performance reasons.

Javascript won't look through the whole global scope to see if x already exists somewhere else.


From a general point of view, first version will be for an index that must live within loop's scope, while the other one would be any variable in the scope where loop's constructor got invoked.

If you're going to use loop's index inside for loop and this won't be required by others in next lines, better declare the variable with "var" so you'll be sure "x" is for loop's index initialized with 0, while the other one, if other "x" variable is available in this context, this will get overwritten by loop's index - that's you'll have some logical errors -.

참고URL : https://stackoverflow.com/questions/5717126/var-or-no-var-in-javascripts-for-in-loop

반응형