배열내장함수 - indexOf , findIndex

Hoo·2023년 3월 29일
0

indexOf란 ?

  • 배열 안에서 찾으려는 값(searchElement)과 정확하게 일치(===)하는'첫번째' element의 index를 리턴합니다.
const arr = [1, 2, 3, 4];
let number = 3;
console.log(arr.indexOf(number))

//결과값 : 2

findIndex 란 ?

  • 배열에서 값을 찾는 조건을 callback 함수로 전달하고, 배열에서 조건에 맞는 값의 index를 리턴하는 함수
  • 객체를 포함한 배열에서 사용할 수 있다.
  • 일치하는 요소가 두개 일경우에는 가장 먼저 조건이 일치는 객체의 인덱스를 반환한다.
return 표시 안한 화살표 함수

const arr = [
  { color: "red" },
  { color: "blue" },
  { color: "white" },
  { color: "black" },
  { color: "pink" }
];
console.log(arr.findIndex((e) => e.color === "red"))
//결과값 : 0
return 표시한 화살표 함수 
const arr = [
  { color: "red" },
  { color: "blue" },
  { color: "white" },
  { color: "black" },
  { color: "pink" }
];

console.log(
  arr.findIndex((e) => {
    return e.color === "red";
  })
);

//결과값 : 0
화살표 함수 사용안한 함수
const arr = [
  { color: "red" },
  { color: "blue" },
  { color: "white" },
  { color: "black" },
  { color: "pink" }
];

console.log(arr.findIndex(function(e){
  return e.color === "pink";
}))

//결과값 : 0

위 예제를 해석하면 arr배열을 한번씩 순회를 하고 color : red 라는 객체가 e라는 파라미터로 들어오게 되고 color:red 와 일치하게 되므로 0을 반환했다.

profile
기록하는중입니다.

0개의 댓글