펭귄집

배열과 객체



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

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


//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의 표준 메서드들을 모두 사용할 수 있다. 



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





 


배열의 프로퍼티 동적 생성



//배열생성

var arr = ['zero','one','two'];
console.log(arr.length);  //(출력값)  3

//프로퍼티 동적 추가
arr.color = 'blue';
arr.name = 'number_array';
console.log(arr.length);  //(출력값)  3

//배열 원소 추가
arr[3] = 'red';
console.log(arr.length);  //(출력값)  4

//배열 객체 출력
console.dir(arr);



arr배열에 동적으로 color와 name프로퍼티를 추가함
주목할점 - 배열에 동적 프로퍼티가 추가될 경우는 배열의 length가 값이 3으로 바뀌지 않는다는것

그런다음 다시 arr[3]에 원소를 추가하면 length가 4로 바뀜


-> 즉, 배열의 length프로퍼티는 배열 원소의 가장 큰 인덱스가 변했을 경우만 변경






배열 요소 삭제



배열도 객체임으로 배열요소나 프로퍼티를 삭제하는데 delete연산자가 사용 가능


var arr = ['zero','one','two','three'];

delete arr[2];
console.log(arr);  //(출력값)  ["zero","one",undefined X1,"three"]
console.log(arr.length);     //(출력값)  4



delete arr[2]로 배열의 요소를 삭제하면, arr[2]에 undefined가 할당된다.
그러나 delete연산자로 배열 요소 삭제 후에도 배열의 length값은 변하지 않는다.

-> 즉, delete 연산자는 해당 요소의 값을 undefined로 설정할 뿐 원소자체를 삭제하지는 않는다.




=> 이때문에 보통 배열에서 요소들을 완전히 삭제할 경우 자바스크립트에서 splice()배열 메서드를 사용한다.







splice() 배열 메서드
splice(start, deleteCount, item ...)
start : 배열에서 시작위치
deleteCount - start에서 지정한 시작 위치부터 삭제할 요소의 수

item - 삭제할 위치에 추가할 요소 




var arr = ['zero','one','two','three'];

arr.splice(2,1);    //2번째 요소를 시작점으로 1개의 원소를 삭제한다
console.log(arr);          //(출력값) ["zero","one","two","three"]
console.log(arr.length);   //(출력값) 3


splice(2,1) 메서드로 arr배열 내 2번째 위치부터 1개의 요소를 삭제했다.


delete연산자와 다르게 배열요소를 완전히 없애게 된다 


-> 따라서 배열 개수도 3





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

배열의 프로퍼티 열거


객체는 for in문으로 프로퍼티를 열거한다.

배열도 객체임으로 for in문으로 사용해서 배열 내의 모든 프로퍼티르 열거할 수 있지만, 
이렇게되면 불필요한 프로퍼티가 출력될 수 있으므로 되도록 for문을 사용하는 것이 좋다. 


for(var prop in arr){
     console.log(prop, arr[prop]);
}

for(var i=0; i<arr.length; i++){
     console.log(i, arr[i]);
}
 


출력결과를 보면 for in문은 0에서 3까지 배열 요소들을 포함해서, color와 name 프로퍼티까지 출력된 반면,


for문은 정확히 배열의 요소만을 정확히 출력하고 있다. 




출력결과


0 zero
1 one
2 two
3 red
color blue
name number_array

0 "zero"
1 "one"
2 "two"
3 "red"




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