반복 메서드 정리
- for ... of
특징 : key 값은 요소가 된다.
for...of 명령문은 반복가능한 객체 (Array, Map, Set, String, TypedArray, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를 생성합니다.
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (let entry of iterable) {
console.log(entry);
}
// [a, 1]
// [b, 2]
// [c, 3]
for (let [key, value] of iterable) {
console.log(value);
}
// 1
// 2
// 3
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for...of
for...of
for...of 명령문은 반복가능한 객체 (Array, Map, Set, String, TypedArray, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를
developer.mozilla.org
- for ... in
특징 : key 값은 property의 인덱스가 된다.
for ... in 문은 객체의 모든 non-Symbol, enumerable properties을 반복합니다.
즉, object에 있는 항목들을 반복적으로 반환하여 '무언가'를 할 수 있게 해줍니다.
const object = { a: 1, b: 2, c: 3 };
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// expected output:
// "a: 1"
// "b: 2"
// "c: 3"
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for...in
for...in
for ... in 문은 객체의 모든 non-Symbol, enumerable properties을 반복합니다.
developer.mozilla.org
for...of와 for...in의 차이
for...in 루프는 객체의 모든 열거가능한 속성에 대해 반복합니다. => 속성/인덱스를 반복
for...of 구문은 컬렉션 전용입니다. 모든 객체보다는, [Symbol.iterator] 속성이 있는 모든 컬렉션 요소에 대해 이 방식으로 반복합니다. => 요소가 반복됨
다음 예는 for...of 루프와 for...in 루프의 차이를 보입니다.
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
console.log(i); // logs 3, 5, 7
}
아래부터 배열의 메소드
- forEach
특징 : 가장 기본적, 모든 요소에 대해 callback을 실행하려하기 때문에 중간에 중단되지 않는다.
예외를 던지지 않고는 forEach()를 중간에 멈출 수 없습니다. 중간에 멈춰야 한다면 forEach()가 적절한 방법이 아닐지도 모릅니다.
다음 방법으로는 조기에 반복을 종료할 수 있습니다.
- 간단한 for 반복문
- for...of, for...in 반복문
- Array.prototype.every()
- Array.prototype.some()
- Array.prototype.find()
- Array.prototype.findIndex()
다른 배열 메서드 every(), some(), find(), findIndex()는 배열 요소를 판별 함수에 전달하고, 그 결과의 참/거짓 여부에 따라 반복의 종료 여부를 결정합니다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Array.prototype.forEach()
forEach() 메서드는 주어진 함수를 배열 요소 각각에 대해 실행합니다.
developer.mozilla.org
- map
특징 : forEach와 똑같지만 callback으로 인해 변화한 배열을 return 함.
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots는 [1, 2, 3]
// numbers는 그대로 [1, 4, 9]
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Array.prototype.map()
map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
developer.mozilla.org
- reduce
특징 : 누적 값을 이용해야 할 때 이용
const callback = (accumulator, currentValue, currentIndex, thisArray) => {
return accumulator
}
// accumulator: 누산기
// currentValue: 처리할 현재 요소
// currentIndex: 처리할 현재 요소의 인덱스
// thisArray: reduce를 호출한 배열
arr.reduce(callback[, initialValue])
// callback: 배열의 각 요소에 대해 실행할 함수
// initialValue: 선택 인자
// 값을 주지 않으면 accumulator는 0 번째 요소, currentValue는 1 번째 요소부터 실행된다.
// 초기값을 주는 것이 바람직하다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Array.prototype.reduce()
reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.
developer.mozilla.org
- every, some
특징: 요소에 대한 판별식 결과 boolean 값을 return 함.
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
every:
어떤 요소에 대해 false가 나오면 즉시 false return.
모든 요소에 대해 true이면 true return.
some:
어떤 요소에 대해 true가 나오면 즉시 true return.
모든 요소에 대해 false이면 false return.
- find, findIndex
판별 함수에 대해 true인 첫번째 요소의 값/인덱스를 return 함.
find: 없는 요소에 대해 undefind return.
findIndex: 없는 요소에 대해 -1 return.