[js]배열내장함수[for Each, map,indexOf,findIndex,find,filter]

young0_0·2022년 11월 14일
0

js

목록 보기
2/10

자바스크립트 배열 내장함수

  • for Each
  • map
  • indexOf
  • findIndex
  • find
  • filter

배열내장함수

For Each

배열안 원소를 일괄적으로 사용할때

const superheros = ["아이어맨", "블랙팬서", "토르", "슈퍼맨"];

superheros.forEach(function (hero) {
  console.log(hero);//아이어맨,블랙팬서,토르,슈퍼맨
});

//화살표함수
superheros.forEach((hero) => {
  console.log(hero);
});

map

배열 안에 원소를 전체적으로 변환 해 주고 싶을때

  • 배열 안에 원소를 변환하여 새로운 배열로 반환한다.
const array = [1,2,3,4,5,6,7,8];
const squared = array.mpa(n => n * n);

console.log(squared)// 1,4,9,16,25,36,49,64

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

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

배열안에 원하는 항목을 찾는 함수

indexOf

특정항목이 몇번째 인덱스에 있는지 알려주는 함수

const superhereo = ["아이어맨", "블랙팬서", "토르", "슈퍼맨"];
const index = superhero.indexOf('토르')
console.log(index); //2

findeIndex

배열이나 객체에서 어떠한 조건으로 찾을때 일치한 조건의 인덱스를 확인하는 함수

  • 가장 첫번째로 찾은 것을 보여준다.

find

특정 조건으로 객체의 내용을 찾는 함수

  • 가장 첫번째로 찾은 것을 보여준다.
const todos = [
  {
    id: 1,
    text: "자바스크립트 입문",
    done: true
  },
  {
    id: 2,
    text: "함수 배우기",
    done: true
  },
  {
    id: 3,
    text: "객체와 배열 배우기",
    done: true
  },
  {
    id: 4,
    text: "배열 내장함수 배우기",
    done: true
  }
];

const findIndex = todos.findIndex(todo => todo.id === 3)
console.log(findIndex) // 2

//find 내장함수
const todo = todos.find(todo => todo.id === 3)
console.log(todo) // {id: 3, text: "객체와 배열 배우기", done: true}

filter

특정조건의 만족하는 원소를 찾아서 그 원소로 새로운 배열을 만드는 함수

  • 기존 배열을 건드리지 않고 새로운 배열을 만든다.
const tasksNotDone =  todos.filter((todo) => !todo.done);
console.log(tasksNotDone) ////id: 4 text: "배열 내장함수 배우기" done: false
profile
열심히 즐기자ㅏㅏㅏㅏㅏㅏㅏ😎

0개의 댓글