티스토리 뷰

728x90
반응형

배열 내장함수 - forEach

1. 기본적인 반복문

const animals = ["개", "고양이", "햄스터", "도마뱀"];

for (let i = 0; i < animals.length; i++) {
  console.log(animals[i]);
}

 

 

2. for ... of 를 사용한 반복문

const animals = ["개", "고양이", "햄스터", "도마뱀"];

for (let animal of animals) {
  console.log(animal);
}

 

 

3. forEach - 내부 함수를 regular function 으로 표현

const animals = ["개", "고양이", "햄스터", "도마뱀"];

animals.forEach( function (animal) {
  console.log(animal);
});

 

 

4. forEach - 내부함수를 arrow function 으로 표현

더 간결하고 깔끔하다.

const animals = ["개", "고양이", "햄스터", "도마뱀"];

animals.forEach((animal) => {
	console.log(animal);
});

 

 


 

배열의 내장함수 - map

const numbers = [ 1,2,3,4,5 ] ;

const square = n => n * n ;

const squre_result = numbers.map(square);

위의 코드는 이해가 될지 모르겠지만 배열의 원소를 square 함수로 적용시켜버리는 것이다.

위의 map의 결과는 아래의 forEach문, for ... of 문의 결과와 같다. 

const numbers = [ 1, 2, 3, 4, 5 ];

// forEach
square_forEach = []
numbers.forEach( n => {
	square_forEach.push( n * n );
});


// for ... of
square_forOf = []
for( let n of numbers ){
	square_forOf.push( n * n ); 
}

 

 

indexOf - 목표값이 배열에 위치한 인덱스를 리턴

목표값이 배열에 존재하지 않는다면 -1 을 리턴한다.

const pokemons = [ '피카츄', '라이츄', '파이리', '꼬부기', '버터플' ];

const kkobuki_idx = pokemons.indexOf('꼬부기'); // 3

 

 

findIndex -  조건에 알맞는 원소의 인덱스를 리턴

find - 조건에 알맞는 원소 자체를 리턴

 

findIndex는 배열 요소가 객체일 때, 조건에 알맞는 객체의 인덱스를 리턴한다.

만일 조건에 알맞는 객체가 여러개인 경우에는 맨앞의 인덱스를 리턴한다.

 

find 도 마찬가지로, 조건에 알맞는 (가장 맨앞의) 원소 그자체 를 리턴한다.

const pokemons = [
  {id: 1, name: "이상해씨", type: "풀"},
  {id: 2, name: "파이리", type: "불"},
  {id: 3, name: "꼬부기", type: "물"},
  {id: 4, name: "버터플", type: "벌레"},
  {id: 5, name: "피카츄", type: "전기"},
  {id: 6, name: "캐이시", type: "에스퍼"},
  {id: 7, name: "푸린", type: "노말"},
  {id: 8, name: "라이츄", type: "전기"}
];

const type_electric = pokemons.findIndex( p => p.type === "전기");
console.log(type_electric); // 4


const type_psychic = pokemons.find( p => p.type === "에스퍼");
console.log(type_psychic); // {id: 6, name: "캐이시", type: "에스퍼"}

 

 


 

배열의 내장함수 - filter

filter 은 조건을 만족하는 요소를 원소로하는 새로운 배열을 생성한다.

const tasks =[
	{ id: 1, subject: '자바스크립트 함수 배우기', done: true },
    { id: 2, subject: '배열의 내장함수 배우기', done: true },
    { id: 3, subject: 'typescript 배우기', done: false },
    { id: 4, subject: 'rxjs 배우기', done: false }
];

const taskNotDone = tasks.filter( task => !task.done );
console.log( taskNotDone );
/*
	(2) [Object, Object]
	0: Object
	id: 3
	subject: "typescript 배우기"
	done: false
	
    1: Object
	id: 4
	subject: "rxjs 배우기"
	done: false
*/



const taskDone = tasks.filter( task => task.done );
console.log( taskDone );
/*
	(2) [Object, Object]
	0: Object
	id: 1
	subject: "자바스크립트 함수 배우기"
	done: true

	1: Object
	id: 2
	subject: "배열의 내장함수 배우기"
	done: true
*/
728x90
반응형

'Backend > Typescript & Angular' 카테고리의 다른 글

shift/unshift & push/pop & concat & join  (0) 2021.08.28
splice & slice  (0) 2021.08.27
array & 반복문(for ... of, for ... in)  (0) 2021.08.24
객체 기본  (0) 2021.08.23
함수  (0) 2021.08.22
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함