프론트엔드/JAVASCRIPT

[javascript] 유사배열과 배열의 차이점 및 공통점 정리

진기명기 2023. 3. 7. 00:18
🫠 배열인 듯 배열이 아닌 유사배열에 대해 정리해 보자.

 

 

 


배열과 유사배열을 생성해 보자
/* 배열과 유사배열 */

let arr = [10, 20, 'yj', 'sh', true]

let not_arr = {
  0: 10,
  1: 20,
  2: 'yj',
  3: 'sh',
  4: true
}

console.log(arr) // [ 10, 20, 'yj', 'sh', true ]
console.log(not_arr) // { '0': 10, '1': 20, '2': 'yj', '3': 'sh', '4': true }
👉🏻 output : 주석 처리 확인
✅  배열인 arr와 배열인 척하는 유사배열인 not_arr를 생성하여 출력해 보았다.

 

 

 

🫠 유사배열이 배열인지 확인해 보자

/* 배열과 유사배열 */

let arr = [10, 20, 'yj', 'sh', true]

let not_arr = {
  0: 10,
  1: 20,
  2: 'yj',
  3: 'sh',
  4: true
}

console.log(Array.isArray(arr)) // true
console.log(Array.isArray(not_arr)) // false
👉🏻 output : 주석 처리 확인
✅  arr은 Array.isArray로 확인했을 때, true가 출력되지만, not_arr는 false를 출력한다.

 

 

 

🫠 배열과 유사배열의 공통점

/* 배열과 유사배열 */

let arr = [10, 20, 'yj', 'sh', true]

let not_arr = {
  0: 10,
  1: 20,
  2: 'yj',
  3: 'sh',
  4: true
}

console.log(arr[0]) // 10
console.log(not_arr[0]) // 10
console.log(arr[3]) // sh
console.log(not_arr[3]) // sh
👉🏻 output : 주석 처리 확인
✅  배열인 arr와 유사배열인 not_arr의 요소에 접근하는 방식 중 위치를 사용하면 같은 값을 출력하는 것을 알 수 있다.

 

 

 

🫠 배열과 유사배열의 차이점

// 유사배열
let not_arr = {
  0: 10,
  1: 20,
  2: 'yj',
  3: 'sh',
  4: true,
}

console.log(not_arr.length) // undefined
👉🏻 output : 주석 처리 확인
✅  유사배열은 배열이 아니기 때문에 array의 속성(메서드)을 전부 사용할 수 없다. 

 

 

 

❗️ 만약 유사배열의 길이를 알고 싶다면?

/* 유사배열 */

let not_arr = {
  0: 10,
  1: 20,
  2: 'yj',
  3: 'sh',
  4: true,
  length: 6
}

console.log(not_arr['length']) // 6
console.log(not_arr.length) // 6
👉🏻 output : 주석 처리 확인
✅  유사배열 내 요소에 length를 따로 추가하여 접근해서 출력할 수 있다. 
❗️ 대괄호를 사용하여 길이를 출력할 수 있고, dot(.)을 이용하여 length 요소에 접근할 수 있지만, dot의 경우 문자열만 접근이 가능하다. 만약 0~4의 요소에 접근하기 위해 'not_arr.0'을 할 경우, 문자가 아닌 숫자이기 때문에 접근이 불가능하다.