객체의 열거형 속성들을 모두 적절한 순서에 의해 반복하게 한다. 각 속성은 주어진 문장을 실행할 수 있다.
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
문법
for (variable in object) { ... }
파라메터
variable
- 매번 반복마다 다른 속성이름 variable로 지정된다.
object
- 반복할 객체로 열거형 속성이 반복적으로 실행한다.
설명
for...in
반복문은 비열거형 속성을 가진 객체는 반복하지 않는다. 즉, Array
같은 내장 생성자에서 생성한 객체들과 Object.prototype
과 String.prototype
은 열거형이 될 수 없으므로 비열거형 속성을 상속한 객체가 된다. 이와 같은 비열거형에 String
indexOf()
메서드 혹은 Object
의
toString()
메서드가 있다. 반복루프는 객체의 모든 열거 속성들을 그리고 객체가 상속받은 생성자의 prototype 반복한다.
A for...in
은 적절한 순서(여기에 대해 delete
operator를 참조하라 )에 맞춰 반복한다. 그런데 반복중에 이전 반복시 사용한 객체의 속성에 변경이 있으면 반복중에는 지난 값이 참조된다. 반복중에 반복하지 않은 속성이 제거된다면 이 속성은 빠지고 반복이 진행된다. 반복중에 속성이 추가되면 반복이 진행되며 이 속성을 반복한다. 그렇지만 반복중에 객체의 속성을 추가, 수정, 삭제하지 않는 것이 가장 좋다. There is no guarantee whether or not 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 and it 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 propertyIsEnumerable
or the non-standard for...of
loop) when iterating over arrays where the order of access is important.
Iterating over own properties only
객체 자체의 속성만을 고려한다면 getOwnPropertyNames()
을 사용하거나 hasOwnProperty()
속성 (propertyIsEnumerable
도 사용)사용을 한다. 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 */
See also
for...of
- a similar statement that iterates over the property valuesfor each in
- a similar statement, but iterates over the values of object's properties, rather than the property names themselves (deprecated)for
- Generator expressions (uses the
for...in
syntax) - Enumerability and ownership of properties
Object.getOwnPropertyNames()
Object.prototype.hasOwnProperty()
Array.prototype.forEach()