JavaScript/배열(Array)
[JavaScript] 배열의 길이 확인하기 (length)
효니님
2024. 7. 22. 01:51
728x90
배열의 길이 확인하기
배열의 길이는 배열에 포함된 요소의 개수를 나타냅니다.
.length 속성을 사용하여 배열의 요소 수를 얻을 수 있습니다.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.length); //3
배열의 길이 설정하기
.length 속성을 사용하여 배열의 크기를 변경할 수 있습니다.
배열의 길이를 줄이면 그 길이 이후에 있는 요소는 삭제됩니다.
const fruits = ["apple", "banana", "cherry"];
fruits.length = 2;
console.log(fruits); // ["apple", "banana"]
배열의 길이 늘리기
배열의 길이를 늘리면 그 길이만큼 새로운 빈 요소가 추가됩니다.
이는 새로운 요소가 undefined로 채워진다는 의미입니다.
const fruits = ["apple", "banana"];
fruits.length = 5;
console.log(fruits); // ["apple", "banana", undefined, undefined, undefined]
.length는 함수가 아니라 속성(미리 계산된 값)입니다. 그렇기 때문에 뒤에 ()를 붙이면 안 됩니다.
728x90