SyntaxError: for-in loop head declarations may not have initializers

이 문서는 아직 자원 봉사자들이 한국어로 번역하지 않았습니다. 참여해서 번역을 마치도록 도와 주세요!
English (US)의 문서도 읽어보세요.

Message

SyntaxError: for-in loop head declarations may not have initializers (Firefox)

SyntaxError: for-in loop variable declaration may not have an initializer. (Chrome)

Error type

SyntaxError in strict mode only.

What went wrong?

The head of a for...in loop contains an initializer expression. That is, a variable is declared and assigned a value |for (var i = 0 in obj)|. In non-strict mode, this head declaration is silently ignored and behaves like |for (var i in obj)|. In strict mode, however, a SyntaxError is thrown.

Examples

This example throws a SyntaxError:

"use strict";

var obj = {a: 1, b: 2, c: 3 }; 

for (var i = 0 in obj) { 
  console.log(obj[i]);
}

// SyntaxError: for-in loop head declarations may not have initializers

Valid for-in loop

You can remove the initializer (i = 0) in the head of the for-in loop.

"use strict";

var obj = {a: 1, b: 2, c: 3 };

for (var i in obj) {
  console.log(obj[i]);
}

Array iteration

The for...in loop shouldn't be used for Array iteration. Did you intend to use a for loop instead of a for-in loop to iterate an Array? The for loop allows you to set an initializer then as well:

var arr = [ "a", "b", "c" ] 

for (var i = 2; i < arr.length; i++) { 
  console.log(arr[i]); 
}

// "c"

See also

  • for...in
  • for...of – also disallows an initializer in both strict and non-strict mode.
  • for – preferred for array iteration, allows to define an initializer.

문서 태그 및 공헌자

 이 페이지의 공헌자: fscholz, WayneCui
 최종 변경: fscholz,