aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/javascript/reference/statements/for...in/index.html
blob: 983e50c91f77cc36b585060141f44db7dac4bd4b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
---
title: for...in
slug: Web/JavaScript/Reference/Statements/for...in
tags:
  - JavaScript
  - Statement
translation_of: Web/JavaScript/Reference/Statements/for...in
---
<div>{{jsSidebar("Statements")}}</div>

<p><code>for...in</code>문은 상속된 열거 가능한 속성들을 포함하여 객체에서 문자열로 키가 지정된 모든 열거 가능한 속성에 대해 반복합니다. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">Symbol</a>로 키가 지정된 속성은 무시합니다.)</p>

<p>{{EmbedInteractiveExample("pages/js/statement-forin.html")}}</p>

<h2 id="Syntax" name="Syntax">문법</h2>

<pre class="syntaxbox notranslate">for (<var>variable</var> in <var>object</var>) {<em> ... </em>}</pre>

<h3 id="Parameters" name="Parameters">파라미터</h3>

<dl>
 <dt><code>variable</code></dt>
 <dd>매번 반복마다 다른 속성이름(Value name)이 변수(<em>variable)</em>로 지정됩니다.</dd>
 <dt><code>object</code></dt>
 <dd>반복작업을 수행할 객체로 열거형 속성을 가지고 있는 객체.</dd>
</dl>

<h2 id="Description" name="Description">설명</h2>

<p><code>for...in</code>문은 열거 가능한 non-Symbol 속성에 대해서만 반복합니다.<br>
 <code>Array</code><code>Object</code> 등 내장 constructor를 통해 만들어진 객체는  {{jsxref("String")}}의 {{jsxref("String.indexOf", "indexOf()")}}, {{jsxref("Object")}}의 {{jsxref("Object.toString", "toString()")}}와 같이 <code>Object.prototype</code>, <code>String.prototype</code> 로부터 열거가 가능하지 않은 속성들을 상속해왔습니다. <code>for...in</code>문은 객체 자체의 모든 열거 가능한 속성들과 프로토타입 체인으로부터 상속받은 속성들에 대해 반복할 것입니다. (더 가까운 프로토타입의 속성들이 프로토타입 체인 객체로부터 더 멀리 떨어진 프로토 타입의 속성보다 더 우선합니다.)</p>

<h3 id="속성의_삭제_추가_수정">속성의 삭제, 추가, 수정 </h3>

<p><code>for..in</code> 문은 임의의 순서로 객체의 속성들에 대해 반복합니다. (적어도 <code>cross-browser</code> 설정에서는 왜 표면적으로 보이는 반복의 순서를 따를 수 없는지에 대해서  {{jsxref("Operators/delete", "delete")}} 를 참고하십시오.)</p>

<p>만약 한 반복으로 속성이 수정된 후에 방문하는 경우, 반복문에서의 그 값은 나중의 값으로 정해집니다. 방문하기 전에 삭제된 속성에 대해서는 이후에 방문하지 않습니다. 반복이 발생하는 객체에 추가된 속성은 방문하거나 반복에서 생략할 수 있습니다.</p>

<p>일반적으로 현재 방문 중인 속성 외에는 반복하는 동안 객체의 속성을 추가, 수정, 제거하지 않는 것이 가장 좋습니다. 추가된 속성을 방문할 것인지, 수정된 속성(현재의 속성 제외)을 수정 이전 혹은 이후에 방문할 것인지, 삭제된 속성을 삭제 이전에 방문할 것인지에 대해서는 보장할 수 없습니다.</p>

<h3 id="배열의_반복과_for...in">배열의 반복과 for...in</h3>

<div class="note" id="arrayNote">
<p><strong>Note: <code>for...in</code></strong> 인덱스의 순서가 중요한<strong> </strong>{{jsxref("Array")}}에서 반복을 위해 사용할 수 없습니다.</p>
</div>

<p>배열 인덱스는 정수로 된 열거 가능한 속성이며, 일반적인 객체의 속성들과 같습니다. <code>for...in</code>은 특정 순서에 따라 인덱스를 반환하는 것을 보장할 수 없습니다. <code>for...in</code>반복문은 정수가 아닌 이름을 가진 속성, 상속된 모든 열거 가능한 속성들을 반환합니다.</p>

<p>반복되는 순서는 구현에 따라 다르기 때문에, 배열의 반복이 일관된 순서로 요소를 방문하지 못할 수도 있습니다. 그러므로 방문의 순서가 중요한 배열의 반복시에는 숫자 인덱스를 사용할 수 있는 <code>for</code> 반복문을 사용하는 것이 좋습니다.(또는 {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Statements/for...of", "for...of")}}를 권장합니다.)</p>

<h3 id="자체_속성만_반복">자체 속성만 반복</h3>

<p>만약 당신이 객체의 프로토타입이 아닌 객체 자체에 연결된 속성만 고려한다면 {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}}나 {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}를 사용하십시오.({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable()")}} 또한 가능합니다.)  또는 외부적인 코드 간섭이 없다면 체크 메서드로 내장 프로토타입을 확장할 수 있습니다.</p>

<h2 id="왜_for...in을_사용합니까">왜 for...in을 사용합니까?</h2>

<p><code>for...in</code>이 객체의 반복을 위해 만들어졌지만, 배열의 반복을 위해서는 추천되지 않고,  <code>Array.prototype.forEach()</code><code>for...of</code>가 이미 존재합니다. 그러면 for...in은 어떻게 사용하는 것이 좋을까요?</p>

<p>이것은 쉽게 객체의 속성을 확인(콘솔이나 다른 방법으로 출력)할 수 있기 때문에 실질적으로 디버깅을 위해 사용될 수 있습니다. 배열이 데이터의 저장에 있어서는 더 실용적이지만, 키-값 쌍이 선호되는 데이터의 경우(속성이 "key"의 역할을 함) 특정 값을 가진 키가 있는지 확인하려는 경우에 for...in을 사용할 수 있습니다.</p>

<h2 id="Example" name="Example">예제</h2>

<h3 id="for...in의_사용">for...in의 사용</h3>

<p>아래의 예는 열거 가능한 non-Symbol속성들을 반복해서 속성의 이름과 그 값을 기록합니다.</p>

<pre class="notranslate"><code>var obj = {a: 1, b: 2, c: 3};

for (const prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"</code></pre>

<h3 id="자체_속성_반복">자체 속성 반복</h3>

<p>아래는 {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}} 를 사용하는 예를 보여주고 있습니다. 상속된 속성은 표시되지 않습니다.</p>

<pre class="brush: js notranslate">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 */
</pre>

<h2 id="상세">상세</h2>

<table>
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}</td>
   <td>{{Spec2('ES3')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}</td>
   <td>{{Spec2('ES1')}}</td>
   <td>Initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="브라우저_호환성">브라우저 호환성</h2>

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

<p>{{Compat("javascript.statements.for_in")}}</p>

<h2 id="Compatibility_Initializer_expressions_in_strict_mode">Compatibility: Initializer expressions in strict mode</h2>

<p>Prior to SpiderMonkey 40 {{geckoRelease(40)}}, it was possible to use an initializer expression (<code>i=0</code>) in a <code>for...in</code> loop:</p>

<pre class="notranslate"><code>var obj = {a: 1, b: 2, c: 3};
for (var i = 0 in obj) {
  console.log(obj[i]);
}
// 1
// 2
// 3</code></pre>

<p>This nonstandard behavior is now ignored in version 40 and later, and will present a {{jsxref("SyntaxError")}} ("<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-in_initializer">for-in loop head declarations may not have initializers</a>") error in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> ({{bug(748550)}} and {{bug(1164741)}}).</p>

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

<h2 id="관련_문서">관련 문서</h2>

<ul>
 <li>{{jsxref("Statements/for...of", "for...of")}} – a similar statement that iterates over the property <em>values</em></li>
 <li>{{jsxref("Statements/for_each...in", "for each...in")}} {{deprecated_inline}} – a similar but deprecated statement that iterates over the values of an object's properties, rather than the property names themselves</li>
 <li>{{jsxref("Statements/for", "for")}}</li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Generator expressions</a> (uses the <code>for...in</code> syntax)</li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li>
 <li>{{jsxref("Object.getOwnPropertyNames()")}}</li>
 <li>{{jsxref("Object.prototype.hasOwnProperty()")}}</li>
 <li>{{jsxref("Array.prototype.forEach()")}}</li>
</ul>