Javascript/배열

Javascript 배열 내장함수(forEach, map, indexOf, findIndex, find)

appmaster 2021. 1. 31. 18:16

1. forEach문

const superheroes = [
    '아이언맨',
    '캡틴 아메리카',
    '토르',
    '닥터 스트레인지'
]

function print(hero){
    console.log(hero);
}

superheroes.forEach(print);
//출력값
아이언맨
캡틴 아메리카
토르
닥터 스트레인지

모두 내장되어있는 데이터를 전부 출력할 수 있는 편리한 기능입니다.

 

 

또한 더 짧게 만들 수도 있습니다.

const superheroes = [
    '아이언맨',
    '캡틴 아메리카',
    '토르',
    '닥터 스트레인지'
]

superheroes.forEach(function(hero){
    console.log(hero);
});

 

 

더깔끔하게 화살표 함수를 이용할 수 있습니다.

const superheroes = [
    '아이언맨',
    '캡틴 아메리카',
    '토르',
    '닥터 스트레인지'
]

superheroes.forEach(hero =>{
    console.log(hero);
});

 

 

 

2. map

* 배열안에 있는 값을 변경하고싶을때 간단하게 사용됩니다.

const array = [1,2,3,4,5,6,7,8];

const squre = n=>n*n;
const squred = array.map(squre);

console.log(squred);
//출력값
[
   1,  4,  9, 16,
  25, 36, 49, 64
]

 

더 간단하게 만들 수 있습니다.

const array = [1,2,3,4,5,6,7,8];

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

console.log(squred);

 

 

*객체로 이루어진 내용중, 원하는값을 배열로 출력이 가능합니다.

const items=[{
    id:1,
    text: 'hello'
}, {
    id:2,
    text: 'bye'
}];

const texts = items.map(item=>item.text);
console.log(texts);
//출력값
[ 'hello', 'bye' ]

 

 

 

3.indexOf

배열안에 있는 값이 몇번째 원소인지 찾아볼 수 있습니다.

const superheroes = [
    '아이언맨',
    '캡틴 아메리카',
    '토르',
    '닥터 스트레인지'
]

const index = superheroes.indexOf('토르');
console.log(index);
//출력값
2

 

 

 

4.findIndex

배열안에 객체이거나 조건을 이용해서 값을 찾을때 이용할 수 있습니다.

const items=[{
    id:1,
    text: 'hello',
    done: true
}, {
    id:2,
    text: 'bye',
    done: true
},{
    id:3,
    text: 'good',
    done: true
},{
    id:3,
    text: 'nice',
    done: false
}];

const index = items.findIndex(item=>item.id ===2)
console.log(index);
//출력값
1

 

 

 

5.find

find와 비슷한 원리지만, 차이점은 find는 객체 그 자체를 반환해줍니다.

const items=[{
    id:1,
    text: 'hello',
    done: true
}, {
    id:2,
    text: 'bye',
    done: true
},{
    id:3,
    text: 'good',
    done: true
},{
    id:3,
    text: 'nice',
    done: false
}];

const index = items.find(item=>item.id ===2)
console.log(index);
//출력값
{ id: 2, text: 'bye', done: true }