[JS] fill

2022. 1. 3. 22:14Javascript/개념

 1. fill() 

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

 

 파라미터 

value

배열에 채울 값을 지정합니다.

 

start

value 값을 채울 배열의 시작 index입니다.

입력하지 않으면 기본값은 0입니다.

 

end

value 값을 채울 배열의 종료 index입니다.

입력하지 않으면 기본값은 배열의 길이(arr.length)입니다.

 

 리턴값 

지정한 값으로 채워진 배열을 리턴합니다.

 

const arr1 = [1, 1, 1, 1];
console.log(arr1.fill(2)); // [2, 2, 2, 2]

const arr2 = [1, 1, 1, 1];
console.log(arr2.fill(2, 1)); // [ 1, 2, 2, 2 ]

const arr3 = [1, 1, 1, 1];
console.log(arr3.fill(2, 1, 3)); // [ 1, 2, 2, 1 ]

 

 

2. index가 음수일 때 

const arr = [1, 1, 1, 1];
const result = arr.fill('A', -3, -1);

console.log(result) // [ 1, 'A', 'A', 1 ]

start나 end index가 음수로 지정되면

배열의 마지막 원소의 index가 -1이 되고,  앞으로 올수록 인덱스가 감소

 

 

 

3. 배열 선언과 동시에 값 채워넣기

const arr = new Array(4).fill('A');
console.log(arr); // [ 'A', 'A', 'A', 'A' ]

 

배열 리터럴 표기법 

let fruits = ['사과', '바나나']

console.log(fruits.length) // 2
console.log(fruits[0])     // "사과"

 

 

단일 매개변수 배열 생성자

let fruits = new Array(2)

console.log(fruits.length) // 2
console.log(fruits[0])     // undefined

 

복수 매개변수 배열 생성자

let fruits = new Array('사과', '바나나')

console.log(fruits.length) // 2
console.log(fruits[0])     // "사과"

 

 

 

'Javascript > 개념' 카테고리의 다른 글

[JS] 데이터 속성 (data-xxx)  (0) 2022.01.10
[JS] 동작원리 (Stack, Queue, event loop)  (0) 2022.01.04
[JS] event.preventDefault()  (0) 2021.12.16
[JS] Filter()  (0) 2021.12.15
[JS] 마우스 이벤트 종류  (0) 2021.12.10