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
'JavaScript > 배열(Array)' 카테고리의 다른 글
| [JavaScript] 배열 중간에 요소 추가, 삭제하기 - splice() (0) | 2023.09.11 |
|---|---|
| [JavaScript] 배열의 첫 번째 값, 마지막 값 가져오기 (0) | 2023.09.11 |
| [JavaScript] 배열 앞, 뒤에 요소 추가, 삭제하기 - unshift(), push(), shift(), pop() (0) | 2023.09.11 |
| [JavaScript] 배열 선언하기 (0) | 2023.09.07 |
| [HTML/CSS] input 태그 입력 필드 비활성화 하는 2가지 방법 (0) | 2023.09.06 |