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 }
'Javascript > 배열' 카테고리의 다른 글
Javascript 배열 내장함수(reduce) 숫자와 문자 다루기 (0) | 2021.02.01 |
---|---|
Javascript 배열 내장함수(shift, pop, unshift, push, concat, join) (0) | 2021.01.31 |
Javascript 배열 내장함수(filter, splice&slice) (0) | 2021.01.31 |
Javascript 배열 반복문 (for...of, for...in) (0) | 2021.01.31 |
Javascript 배열의 특징(push, length) (0) | 2021.01.31 |