JavaScript/배열(Array)

[JavaScript] 배열의 길이 확인하기, 설정하기 (length 속성)

효니님 2023. 9. 8. 16:25
728x90

 

 

 

배열의 길이를 확인하기 위해서는 

Array 인스턴스의 length속성을 사용합니다.

 

 

1. 배열의 길이 확인하기

const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing); // ['shoes', 'shirts', 'socks', 'sweaters']
console.log(clothing.length); // 4

clothing배열의 길이를 확인해 보니 4인 것을 확인할 수 있습니다.

 

 

2. 배열의 길이 설정하기

const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
clothing.length = 3;
console.log(clothing); // ['shoes', 'shirts', 'socks']
console.log(clothing.length); // 3

length 속성에 값을 설정해 배열의 길이를 절단할 수 있습니다.

또한 배열의 길이를 늘리는 것도 가능합니다.

 

const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
clothing.length = 6;
console.log(clothing); // ['shoes', 'shirts', 'socks', 'sweaters', empty × 2]

length 속성으로 배열의 길이를 6으로 늘렸더니 

기존 원소 4개에서 마지막 undefined가 2개 추가되어 총 6개의 길이를 갖게 됩니다.

 

 

728x90