The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
for 문은 괄호 안의 3개의 표현으로 구성된 루프를 생성한다. 그리고 루프 안에서 실행될 서술문이 뒤따른다.
for ([initialization]; [condition]; [final-expression]) {
statement
}
The forEach() method executes a provided function once for each array element.
forEach 문은 각 어레이의 요소마다 주어진 함수를 실행한다.
arr.forEach(function (value) {
statement
})
for 문은 루프에서 빨리 빠져나올 수 있다: 만약 for 문 안에서 if를 쓰는 경우라면 조건에 맞는 경우, 바로 루프를 빠져 나간다. 하지만 forEach는 각 요소를 한 번씩 접근해야 한다.
for each가 훨씬 간결해 읽기 쉽다: for 문에서는 어레이에 접근할 때 보통 일시적인 변수인 i를 사용해 되는데 코드가 복잡해질 시 헷갈리게 쓰여질 수 있다.
const foodArray = [
{ name: 'Burrito' },
{ name: 'Pizza' },
{ name: 'Burger' },
{ name: 'Pasta' }
];
//for 문의 예시
for (let i = 0; i < foodArray.length; i++) {
let food = foodArray[i];
console.log(food);
for (let j = 0; j < food.ingredients.length; j++) {
let ingredient = food.ingredients[j];
console.log(ingredient);
}
}
//for each 문의 예시
foodArray.forEach((food) => {
console.log(food);
food.ingredients.forEach((ingredient) => {
console.log(ingredient);
});
});
The "for...in" statement creates a loop that iterates over all non-symbol, enumerable properties of an object, sometimes in an arbitrary order.
for...in 서술은 오브젝트의 모든 셀수 있는 프로퍼티?에 대해 반복하게 되고 때때로는 임의의 순서대로 진행된다. 어레이는 인덱스 순서가 중요하기 때문에 for...in을 사용해서는 안된다.
for (variable in object)
statement
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"
The "for...of" statement creates a loop that iterates over iterable objects in iterable order. A common use is looping through values in an array, but it also works on most array-like objects.
for...of 문은 순서를 가지고 오브젝트에 대해 반복하는 루프를 만들게 된다. 보통 어레이의 밸류를 반복 실행하게 된다. 하지만 유사배열에도 작동한다.
for (variable of iterable) {
statement
}
const iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
forEach와는 다르게 for...of 에서는 break, continue, return을 사용할 수 있다.
for...in과는 다르게 for...of는 어레이의 인덱스에 접근하는데 오름차순의 순으로 접근한다. 그리고 어레이의 인덱스가 스트링으로 변환되지 않기 때문에 산수를 적용할 수 있다.
property: 이름과 값으로 이루어져 있으며 간단하게 오브젝트의 데이터 값이라고 생각하면 될 것 같다.
enumerable property: 오브젝트의 각 프로퍼티는 자신만의 내부 프로퍼티, 즉 사용자가 접근할 수는 없지만 자바스크립트 엔진에서 사용되는 프로퍼티를 가진다. 그들은 [[Property]]
로 나타낼 수 있다. 모든 오브젝트는 [[Enumerable]]
프로퍼티 속성은 불리안 값을 가지게 되고 propertyIsEnumerable()
로 true인지 false인지 결정지을 수 있다. 값이 true라면 오브젝트가 열거할 수 있는 것이고 for...in 루프 안에서 반복될 수 있다. 값이 false라면 다른 오브젝트에서 동일한 이름의 프로퍼티에게 우위를 뺏겼다는 뜻이고 루프 안에서 반복되지 않을 것이다.