[JS] forEach(), fill()

KJA·2022년 7월 18일
0

forEach() 란?

forEach() 메서드는 배열에 활용이 가능한 메서드로, 파라미터로 주어진 함수를 배열 요소 각각에 대해 실행하는 메서드이다.
map() 메서드와 거의 비슷하지만 차이점은 따로 return 값이 없다.

  • 배열의 반복분
  • 배열에서만 사용하는 메서드
  • 배열의 처음부터 마지막 요소까지 반복하여 실행
  • 인자로 콜백함수를 받아옴
  • 주어진 콜백함수를 배열 요소 각각에 대해 실행
  • querySelectorAll() 전체 선택자를 이용하여 주로 사용

function

const number = [3, 7, 4, 2];
number.forEach(function (element, index) {
    console.log(element, index);
});

// 결과
// 3, 0
// 7, 1
// 4, 2
// 2, 3

화살표 함수

const number = [3, 7, 4, 2];
number.forEach((element, index)=>{
	console.log(element, index);
});

// 결과
// 3, 0
// 7, 1
// 4, 2
// 2, 3

fill()

배열의 start index부터 end index 전까지(end index는 미포함) value값으로 채워주는 함수입니다.

syntax

arr.fill(value [, start [, end]])
  • value : 배열을 채울 값
  • start : 시작 인텍스
  • end : 끝 인덱스 (end가 3이면, 3은 포함되지 않는다)
const arr = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(arr.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(arr.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(arr.fill(6));
// expected output: [6, 6, 6, 6]

console.log(arr.fill()); // fill 인자가 없으므로 undefined 할당됨
// expected output: (4) [undefined, undefined, undefined, undefined]

0개의 댓글