[개념] 자바스크립트 / 배열 내장함수

Eun-jeong Park·2023년 7월 15일

javascript

목록 보기
2/6

  1. forEach()
    -> 배열의 모든 요소를 순회하는 함수

<화살표 함수 방식>

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

결과

"a"
"b"
"c"

<함수선언방식>

const arr = [1, 2, 3, 4];

arr.forEach(function (x) {
  console.log(x);
});

결과

1
2
3
4
  1. map()
    -> 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
const arr = [1, 2, 3, 4];
const newArr = arr.map((x) => {
  return x * 2;
});

console.log(newArr);

결과

[2, 4, 6, 8]
  1. includes()
    -> 배열이 특정 요소를 포함하고 있는지 판별합니다.
const arr = [1, 2, 3, 4];

let number = 3;

console.log(arr.includes(number));

결과

true
  1. indexOf()
    -> 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.

  2. findIndex()
    -> 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.

const arr = {
  { color: "red" },
  { color: "black" },
  { color: "blue" },
  { color: "green" }  
};

let number = 3;

console.log(arr.findIndex((x) => x.color === "red"));

결과

0

일치하는 요소가 여러 개 인 경우에는 제일 첫번째 것을 출력

profile
지구를 사랑하는 개발자

0개의 댓글