Javascript - 배열 내장함수 map

YuJin Lee·2020년 10월 6일
0

Javascript

목록 보기
7/22
  • 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);
//{1, 4, 9, 16, 25, 36, 49, 64}

  • forEach 이용
const array = [1,2,3,4,5,6,7,8]

const squared = [];
array.forEach(i => {
  squared.push(i * i);
});

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

  • map 사용
const array = [1,2,3,4,5,6,7,8]
const squared = array.map(i => i * i);

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

  • indexOf
    배열에서 특정 요소의 순서가 몇번째인지 알려준다.
const array = ['a', 'b', 'c', 'd', 'e'];
const index = array.indexOf('c');
console.log(index);
//2

  • findIndex
    객체로 이루어진 배열에서 순서를 찾을 때는
    indexOf가 아니라 findIndex를 사용해야 한다.
const todos = [
  {
    id: 1,
    text: '함수',
    done: true
  },
  {
    id: 2,
    text: '객체',
    done: true
  },
  {
    id: 3,
    text: '배열',
    done: false
  }
]

const index = todos.findIndex(todo => todo.id === 3);
console.log(index);
//2
//3번째 객체의 id가 3이므로

  • find
    특정 순서의 객체 값을 구하고 싶을 때는 find를 사용한다.
const todos = [
  {
    id: 1,
    text: '함수',
    done: true
  },
  {
    id: 2,
    text: '객체',
    done: true
  },
  {
    id: 3,
    text: '배열',
    done: false
  }
]

const todo = todos.find(todo => todo.id === 3);
console.log(todo);
//Object {id: 3, text: "배열", done: false}
//3번째 객체의 값 출력
profile
배운 것을 기록하는 곳 💻🙂

0개의 댓글