펭귄집

배열과 객체



자바스크립트에서 배열 역시 객체

하지만 배열은 일반객체와 약간의 차이가 있다.


//1번
//colorsArray 배열
var colorsArray = ['orange','yellow','green'];
console.log(colorsArray[0]);  //(출력값)  orange
console.log(colorsArray[1]);  //(출력값)  yellow
console.log(colorsArray[2]);  //(출력값)  green

//colorsObj 객체
var colorObj = {
     '0' : 'orange',
     '1' : 'yellow',
     '2' : 'green'
};
console.log(colorsObj[0]);    //(출력값)  orange
console.log(colorsObj[1]);    //(출력값)  yellow
console.log(colorsObj[2]);    //(출력값)  green

//2번
//typeof 연산자 비교
console.log(typeof colorsArray);  //(출력값) object (not array)
console.log(typeof colorsObj);    //(출력값) object

//3번
//length 프로퍼티
console.log(colorsArray.length);  //(출력값)  3
console.log(colorsObj.length);    //(출력값)  undefined

//4번
//배열 표준 메서드
colorsArray.push('red');           //['orange','yellow','green','red']
colorsObj.push('red');             //Uncaught TypeError: Object #<Object> has no method 'push'


1번 - 배열과 객체 생성
colorSArray배열의 형태와 유사하게 객체 리터럴 방식으로 colorsObj객체를 생성

객체프로퍼티설명할 때, 대괄호 안에는 접근하려는 프로퍼티의 속성을 문자열 형태로 적어야 한다고했음
(colorObj[0]이아니라 colorObj['0']형태로 기입해야 맞는거 BUT 저렇게 안써도 제대로출력됨)

-> 이유는 자바스크립트엔진이 []연산자 내에 숫자가 사용될 경우, 해당 숫자를 자동으로 문자열 형태로 바꿔주기때문


2번 - typeof 연산자 비교
typeof 연산결과는 배열과 객체가 모두 object인걸 기억해야함
-> 즉, 자바스크립트도 배열을 객체로 생각하는 것


3번 length 프로퍼티 존재 여부
배열 colorsArray와 객체 colorObj는 근본적 차이가 있음
colorsObj는 객체이므로 length 프로퍼티가 존재 X

-> colorsArray.length는 3이 출력되지만 colorsObj.length 결과가 undefined인 이유


4번 - 배열 표준 메서드 호출 여부
배열과 객체의 또하나의 차이점은 colorObj는 배열이 아니므로 push()메서드와 같은 표준 배열 메서드를 사용X

-> 배열과 객체가 자신의 부모인 프로토타입 객체가 서로 다르기때문


객체리터럴방식으로 생성한 객체의 경우, 객체 표준 메서드를 저장하고 있는 Object.prototype 객체가 프로토타입.
배열의 경우 Array.prototype 객체가 부모객체인 프로토타입.
Array.prototype객체의 프로토타입은 Object.prototype 객체가 된다.


객체는 자신의 프로토타입이 가지는 모든 프로퍼티 및 메서드들을 상속받아 사용 O이므로 배열은 Array.prototype에 포함된 배열 표준 메서드와 Object.prototype의 표준 메서드들을 모두 사용할 수 있다. 



<참고문헌 : 인사이드자바스크립트>