이 번역은 완료되지 않았습니다. 이 문서를 번역해 주세요.

for ... in 문은 객체의 모든 non-Symbol, enumerable properties을 반복합니다.

즉, object에 있는 항목들을 반복적으로 반환하여 '무언가'를 할 수 있게 해줍니다.

문법

for (variable in object) { ... }

파라메터

variable
매번 반복마다 다른 속성이름(Value name)이 변수(variable)로 지정된다.
object
반복작업을 수행할 객체로 열거형 속성을 가지고 있는 객체.

설명

for...in loop only iterates over enumerable, non-Symbol properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Object.prototype and String.prototype, such as String's indexOf() method or Object's toString() method. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

 

Deleted, added, or modified properties

 

 

for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting).

If a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time. A property that is deleted before it has been visited will not be visited later. Properties added to the object over which iteration is occurring may either be visited or omitted from iteration.

In general, it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited. There is no guarantee whether an added property will be visited, whether a modified property (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.

 

Array iteration and for...in

Note: for..in should not be used to iterate over an Array where index order is important.

 

Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.

 

Iterating over own properties only

If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames() or perform a hasOwnProperty() check (propertyIsEnumerable can also be used). Alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method.

예제

아래 함수는 객체와 객체의 이름을 인자로 받아서 객체의 모든 속성의 이름과 같은 문자열로 반환해주고 있다.

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

function show_props(obj, objName) {
  var result = "";
    
  for (var prop in obj) {
    result += objName + "." + prop + " = " + obj[prop] + "\n";
  }
    
  return result;
}

alert(show_props(o, "o")); /* alerts: o.a = 1 o.b = 2 o.c = 3 */ 

아래는 hasOwnProperty() 를 사용하는 예를 보여주고 있다. 결과적으로 상속한 속성들은 표시되지 않는다.

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

function ColoredTriangle() {
  this.color = "red";
}

ColoredTriangle.prototype = triangle;

function show_own_props(obj, objName) {
  var result = "";
    
  for (var prop in obj) {
    if( obj.hasOwnProperty( prop ) ) {
      result += objName + "." + prop + " = " + obj[prop] + "\n";
    } 
  }
    
  return result;
}

o = new ColoredTriangle();
alert(show_own_props(o, "o")); /* alerts: o.color = red */ 

Specifications

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
The definition of 'for...in statement' in that specification.
Draft  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'for...in statement' in that specification.
Standard  
ECMAScript 5.1 (ECMA-262)
The definition of 'for...in statement' in that specification.
Standard  
ECMAScript 3rd Edition (ECMA-262)
The definition of 'for...in statement' in that specification.
Standard  
ECMAScript 1st Edition (ECMA-262)
The definition of 'for...in statement' in that specification.
Standard Initial definition.

Browser compatibility

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
for...inChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support 6Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support

Compatibility: Initializer expressions in strict mode

Prior to SpiderMonkey 40 (Firefox 40 / Thunderbird 40 / SeaMonkey 2.37), it was possible to use an initializer expression (i=0) in a for...in loop:

var obj = {a: 1, b: 2, c: 3};
for (var i = 0 in obj) {
  console.log(obj[i]);
}
// 1
// 2
// 3

This nonstandard behavior is now ignored in version 40 and later, and will present a SyntaxError ("for-in loop head declarations may not have initializers") error in strict mode (bug 748550 and bug 1164741).

Other engines such as v8 (Chrome), Chakra (IE/Edge), and JSC (WebKit/Safari) are investigating whether to remove the nonstandard behavior as well.

See also섹션

문서 태그 및 공헌자

태그: 
이 페이지의 공헌자: mdnwebdocs-bot, limkukhyun, teoli, Androidbee
최종 변경자: mdnwebdocs-bot,