배열의 data type은 Object이다. 그 이유에 대해 적어보자
(출처 : https://workatit.tistory.com/88)
객체는 서로 연관된 특징과 행동들을 묶어두는 데이터 타입이라고 할 수 있다. 키를 사용해 식별할 수 있는 값(키의 값)을 담은 컬렉션이다.
객체는 태생이 순서를 고려하지 않고 만들어진 자료구조이다. 개발을 하다 보면 첫 번째 요소, 두 번째 요소, 세 번째 요소 등과 같이 순서가 있는 컬렉션이 필요할 때가 있는데, 이 때 객체를 사용하면 순서와 관련된 메서드가 없어 불편하다.
그래서 순서가 있는 컬렉션을 저장해야하는 상황이 생길 때 쓰려고 만든 자료구조가 바로 배열이다.
자바스크립트의 배열은 자료구조에서 말하는 일반적인 배열의 동작을 흉내낸 특별한 종류의 객체이다. 객체처럼 동작하는 부분과 일반적인 배열처럼 동작하는 부분을 나눠서 보자.
arr[0]
처럼 대괄호를 사용하는 방식도 객체 문법에서 왔다.- 배열의 요소 변경하기-
let fruits = ["사과", "오렌지", "망고"]
fruits[2] = '배'
console.log(fruits) // ["사과", "오렌지", "배"]
- 객체 변경하기-
let fruits = {
red: "사과",
orange: "오렌지",
yellow: "망고"
}
fruits.red="딸기"
console.log(fruits)
// 출력
{
orange: "오렌지",
red: "딸기",
yellow: "망고"
}
😀 참조에 의한 전달
let person = {
name: 'Lee'
};
let copy = person;
console.log(copy) ; // {name: 'Lee'}
copy.name = 'Kim';
person.address = 'Seoul';
console.log(person); // {name: 'Kim', address: 'Seoul'}
console.log(copy); // {name: 'Kim', address: 'Seoul'}
let fruits = ["바나나"]
let arr = fruits;
console.log(arr); // ["바나나"]
arr.push("배");
console.log(arr); // ["바나나", "배"]
console.log(fruits); // ["바나나", "배"]
console.log(fruits === arr) // true
-배열-
let fruits = ["사과", "오렌지", "자두"]
console.log(fruits[0]); // 사과
console.log(fruits[1]); // 오렌지
console.log(fruits[2]); // 자두
fruits.push("망고")
console.log(fruits) // ["사과", "오렌지", "자두", "망고"]
console.log(fruits.length) // 4
-객체-
let fruits = {
red: "사과",
orange: "오렌지",
yellow: "망고"
}
console.log(fruits)
//출력
{
orange: "오렌지",
red: "사과",
yellow: "망고"
}