반응형
for
기본적인 반복문이다. 초기식, 조건식, 증감식을 모두 포함하고 있다. 반복문의 3개 식은 모두 선택 사항으로, 생략 가능하다. break을 이용하여 반복문을 중단할 수 있다.
for ([initialization]; [condition]; [final-expression]){
statement
}
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";
for(; i < cars.length; ){
console.log(cars[i]);
i++;
}
// Output :
// "BMW"
// "Volvo"
// "Saab"
// "Ford"
for ...in
객체 순환을 할 때 유용한 반복문으로, key 값을 이용하여 value값에 접근할 수 있다.
const person = {fname:"Molly", lname:"Hong", age:24};
let array = [];
for(let key in person){
array.push(person[key]);
}
console.log(array);
// Output :
// ["Molly", "Hong", 24]
물론 배열에서도 사용할 수 있다. 이때 인덱스 값을 가져온다.
const numbers = [45, 4, 9, 16, 25];
for (let x in numbers) {
let num = numbers[x];
console.log(num);
}
// Output :
// 45
// 4
// 9
// 16
// 25
for ...of
String 문자열 혹은 Array 배열 순회 시 유용하다.
const cars = ["BMW", "Volvo", "Mini"];
for (let x of cars) {
console.log(x);
}
// Output :
// "BMW"
// "Volvo"
// "Mini"
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x;
}
console.log(text);
// Output :
// "JavaScript"
forEach
배열, Set, Map 을 순회하면서 인자로 전달한 함수를 호출하는 반복문으로 유용하게 사용할 수 있다. break을 사용하지 못한다.
arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
const arr = ['apple', 'kiwi', 'grape', 'orange'];
arr.forEach((item) => {
console.log(item);
});
// "apple"
// "kiwi"
// "grape"
// "orange"
const set = new Set();
for(let i=1 ; i<10 ; i++){
set.add(i);
}
set.forEach((item) => {
console.log(item)
});
let map = new Map();
map.set('name', 'John');
map.set('age', '30');
map.forEach ((value) => console.log(value));
// Output:
// "John"
// "30"
객체 배열을 순회할 때 데이터 가공을 할 수도 있다.
const person1 = {fname:"Molly", lname:"Hong", age:24};
const person2 = {fname:"JunJin", lname:"Lee", age:30};
const persons = [person1, person2];
persons.forEach((obj) => {
obj.isOld = obj.age < 30 ? false : true;
});
console.log(persons);
// Output:
// [{
// age: 24,
// fname: "Molly",
// isOld: false,
// lname: "Hong"
// }, {
// age: 30,
// fname: "JunJin",
// isOld: true,
// lname: "Lee"
// }]
map
각 요소에 대해 callback을 실행하고 리턴한 값으로 새로운 배열을 반환한다.
arr.map(callback(currentValue[, index[, array]])[, thisArg])
객체 배열을 다시 재구성하는 예시를 들 수 있다. 이렇게 새로운 값으로 리턴을 할 때 사용하면 유리하다.
const person1 = {fname:"Molly", lname:"Hong", age:24};
const person2 = {fname:"JunJin", lname:"Lee", age:30};
const persons = [person1, person2];
let newPersons = persons.map(function(obj){
let newObj = {};
newObj[obj.fname] = obj.lname + obj.fname;
return newObj;
});
console.log(newPersons);
// Output :
// [{
// Molly: "HongMolly"
// }, {
// JunJin: "LeeJunJin"
// }]
또, 객체 배열의 특정 값만 추출할 때도 간편하다.
const kvArray = [{key:1, value:10},
{key:2, value:20},
{key:3, value: 30}];
const array = kvArray.map((obj) => {
return obj.value;
});
console.log(array);
// [10, 20, 30]
*참고
JavaScript - forEach(), 다양한 예제로 이해하기
forEach()는 배열을 순회하면서 인자로 전달한 함수를 호출하는 반복문입니다. 배열 뿐만 아니라, Set이나 Map에서도 사용 가능합니다. forEach()의 문법은 아래와 같으며, 함수로 value, index, array를 전
codechacha.com
반응형