WEB/Java Script

[Java Script] 배열 내장함수 /forEach : 배열 안의 값 하나씩 출력하기/ map:배열을 활용하여 새로운 배열 만들기/ indexOf: 몇번째 index인지 알려줌/ findIndex: 특정 조건의 index를 알려줌

자바칩 프라푸치노 2021. 4. 23. 18:41
const superheroes = [
  '아이언맨', '캡틴 아메리카','토르','닥터스트레인지'
];

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

superheroes.forEach(print);

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

forEach함수

배열 안의 값을 하나씩 다 출력하기

 


map 

배열에 있는 내용을 전체적으로 변화를 주고 싶을 때

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

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

array배열의 안의 값들을 전부 제곱해서 새로운 배열로 만들어라

 

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

const texts = item.map(item => item.text);
// texts라는 배열에는 item의 text의 값만 넣어서 만든다
console.log(texts);

 

배열 item에서 text값만 꺼내서 새로운 배열 texts를 만들어라


indexOf

찾고자 하는 원소가 몇번째 index인지 알려주는 내장함수

const superheroes = [
  '아이언맨', '캡틴 아메리카','토르','닥터 스트레인지'
]
// 찾고자 하는 원소가 몇번째 index에 있는지 알기위해
const index = superheroes.indexOf('닥터 스트레인지');
console.log(index);

 

 


findIndex

특정 조건을 확인해서 일치하는 요소의 index를 알려주는 내장함수

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


];

// id가 3인것을 찾고 싶다.
// 특정 조건을 확인해서 일치하면 몇번째 요소인지 알려주는 것
const index = todos.findIndex(todo => todo.id ===3)
console.log(index);


find

특정 조건을 만족하는 요소의 배열 index의 값 전체를 출력

const todo = todos.find(todo => todo.done ===false)
console.log(todo);

todo배열에서 done 이 false인 요소의 index의 모든 값을 출력해라

728x90