티스토리 뷰

Java Script & HTML

유사배열객체

LichKing 2017. 5. 6. 19:39

자바스크립트는 배열과 객체의 개념이 모호하다. 정확히 표현하자면 배열도 객체의 하나이긴하지만 배열이 아님에도 배열인척하는 객체들이 충분히 존재하기때문에 헷갈리는 경우가 존재한다. 대표적인게 arguments 객체이다.


var test = function(){
for(var i = 0, size = arguments.length; i < size; i++){
console.log(arguments[i]);
}
};

test("hello", "world");


배열이다. 그냥 배열이다. 반복문 자체도 전형적인 배열 루프다.


console.log(arguments instanceof Array);


하지만 Array의 인스턴스는 아니라고한다.


console.log(Array.isArray(arguments));
console.log(Array.prototype.isPrototypeOf(arguments));
console.log(Object.getPrototypeOf(arguments) === Array.prototype);


이런저런 비교들을 다 해봐도 반환값은 false 뿐이다. 실제 배열들은 어떻게 내려오는지 확인해보자.


var arr = [];
console.log(arr instanceof Array);
console.log(Array.isArray(arr));
console.log(Array.prototype.isPrototypeOf(arr));
console.log(Object.getPrototypeOf(arr) === Array.prototype);


진짜 배열은 모두 true를 반환한다. '저게 false면 어때 그냥 배열처럼 쓸수있으니 배열처럼 쓰면 되잖아' 라고 생각할수도 있으나 Array의 prototype을 체이닝 하지않으므로 Array의 메서드들도 사용할 수 없다. 즉 배열처럼 사용하면 안된다는 것이다.


var test = function(){
arguments.forEach(function(arg){
console.log(arg);
});
};

test("hello", "world");

(이렇게 쓰면 만날 수 있는건... Uncaught TypeError: arguments.forEach is not a function)


그럼 arguments의 정체는 무엇인가? 제일 처음 봤던 예제는 어떻게 작동한다는 말인가?

arguments 는 그저 숫자를 key로 갖고있고, length를 프로퍼티로 갖고있는 객체일 뿐이다.


var test = function(){
var keys = Object.keys(arguments);
console.log(keys);
console.log(arguments.hasOwnProperty("length"));
};

test("hello", "world");


자바스크립트는 객체 자체가 딕셔너리 형태의 연관배열(Associative Array)이므로 객체를 참조할때 . 연산자 외에도 []연산자로 참조할 수 있다.


var obj = {
name : "LichKing"
};

console.log(obj.name);
console.log(obj["name"]);


arguments 처럼 배열인척(?) 하는 객체를 유사배열객체라고 표현하는데 arguments 만이 특별하게 유사배열행세를 하는게 아니라 커스텀한 유사배열객체도 얼마든지 만들 수 있다는 의미이다.


var obj = {
"0" : "hello",
"1" : "world",
"length" : "2"
};


그럼 arguments 가 기왕 배열인척하는김에 진짜 배열들이 체이닝하는 Array.prototype 의 메서드들을 활용하고싶을땐 어떡해야할까?

arguments 에 한땀한땀 구현해주는 방법도 있지만 이런식으로 Array.prototype 을 활용할 수 있다.


var test = function(){
Array.prototype.forEach.call(arguments, function(arg){
console.log(arg);
})
};

test("hello", "world");


'Java Script & HTML' 카테고리의 다른 글

ES5 주요 함수 분석  (0) 2017.05.17
ES5 Array method  (0) 2017.05.13
Strict Mode  (0) 2017.04.30
setTimeout과 custom sleep  (4) 2017.02.12
AngularJS Filter 만들기  (0) 2017.02.03
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함