javascript

배열 내장함수

소영 2021. 5. 1. 01:30

forEach

우리가 알고 있던 for문을 대체

배열의 요소를 반복하여 작업을 수행

[for문 일시]

const superheroes = ['아이언맨','캡틴아메리카','토르','닥터스트레인지'];
for(let i = 0; i< superheroes.length; i++){console.log(superheroes[i]);}

[forEach문]

const superheroes = ['아이언맨','캡틴아메리카','토르','닥터스트레인지'];
superheroes.forEach(hero =>{console.log(hero);})

map(변화를 주는 함수를 전달해주기 때문에 '변화함수'라고 한다.)

배열 안의 각 원소를 변환 할때 사용 됨

[for문을 이용한 배열 정리]

const array = [1,2,3,4,5,6,7,8];
const squared = [];
for(let i = 0; i<array.length; i++){squared.push(array[i]*array[i]);}
console.log(squared);

 

[forEach문을 이용한 배열정리]

const array = [1,2,3,4,5,6,7,8];
const squared =[];
array.forEach(squared.push(n*n););
console.log(squared);

 

[map을 이용한 배열정리]

const array = [1,2,3,4,5,6,7,8];
const square = n => n*n;
const squared = array.map(square);
console.log(squared);

 

하지만, 변화함수는 이름을 꼭 붙일 필요는 없다.

const squared = array.map(n => n*n);

console.log(squared);

const squared = array.map(n => n*n);
console.log(squared);

 

indexOf

원하는 항목이 몇번째 원소인지 찾아주는 함수

const superheroes = ['아이언맨','캡틴아메리카','토르','닥터 스트레인지'];
const index = superheroes.indexOf('토르');
console.log(index);

 

findIndex

배열안에 있는 찾고자 하는 값이 객체이거나,배열이라면 findIndex를 사용해야함

const todos = [
  {
    id: 1,
    text: '자바스크립트 입문',
    done: true
  },
  {
    id: 2,
    text: '함수 배우기',
    done: true
  },
  {
    id: 3,
    text: '객체와 배열 배우기',
    done: true
  },
  {
    id: 4,
    text: '배열 내장함수 배우기',
    done: false
  }
];

const index = todos.findIndex(todo => todo.id === 3);
console.log(index);