Arrary.fill()

국물빌런·2020년 12월 21일
0

Arrary.fill()

fill() 메서드는 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채운 배열을 반환, es6에서 추가됨

여기서 정적인 값은 fill()함수의 인자이며 인자는 총 3개다

1번째 인자는 배열을 채울 값,

2번째 인자는 1번째인자값로 채우기 시작할 인덱스(옵션)

3번째 인자는 1번째인자값으로 채움이 끝날 인덱스(옵션)

start의 기본값은 0, end의 기본값은 배열의 길이

**중요한 점은 해당 함수는 배열을 복사해서 반환하는게 아니라 this로 연산하여 반환함

const array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
profile
국물을 달라

0개의 댓글