본문 바로가기
Front-End/JavaScript

[JavaScript] Objects, Arrays, Array-Like objects

by 김뚱 2019. 3. 28.

1.Objects

[TEST]

var basicObj = {}; //an empty object -> {} is a shortcut for "new Object()"
basicObj.surprise = 'cake';
basicObj['surprise'] // returns "cake"

 

new Object( ); 구문 대신에 { } 을 사용하는 것을 "Object Literal" 구문 이라고 한다.

 

[TEST]

var fancyObj = {
	favoriteFood : 'pizza',
	add : function(a, b) {
		return a + b;
	}
};
fancyObj.add(2,3); // returns 5
fancyObj['add'](2,3); // returns 5

javascript의 모든 것은 object이다. 때문에 Objects, Arrays 등의 prototypes를 수정할 수 있다.

 

[TEST]

Number.prototype.addto = function(x){ 
	return this + x; 
}

(8).addto(9); // returns 17

// other variations:

8.addto(9); // gives a syntax error, because the dot is assumed to be a decimal point

8['addto'](9); // works but is kind of ugly compared to the first method

var eight = 8;

eight.addto(9); // works

 

[실행화면]

 

 

2.Arrays 

Javascript arrays 는(은) 단일 변수에 여러 값을 저장하는 데 사용되는 Object 이다. 
각 값은 숫자 인덱스를 얻으며 모든 데이터 유형일 수 있다.

Arrays 에는 항목의 수를 나타내는 length 속성이 있으며, 항목을 추가하거나 제거할 시 자동으로 업데이트 된다.

길이 속성은 기본 객체가 아닌 배열에 항목을 추가 할 때만 수정된다.

 

[TEST]

var arr = []; // this is a shortcut for new Array(); 
arr[0] = 'cat'; // this adds to the array 
arr[1] = 'mouse'; // this adds to the array

arr.length; // returns 2

arr['favoriteFood'] = 'pizza'; // this DOES NOT add to the array. Setting a string parameter adds to the underlying object

arr.length; // returns 2, not 3

 

[실행화면]

 

배열의 길이는 실제 항목이 적더라도 항상 1 더 높다.

 

[TEST]

var arr = []; 
arr.length; // returns 0; 
arr[100] = 'this is the only item in the array'; 
arr.length; // returns 101, even though there is only 1 object in the array

 

[실행화면]

 

length 속성 외에도 Array 는(은) push(), pop(), sort(), slice(), splice() 등의 기능을 가지고 있다.
이것이 Array-Like objects 와 구분되는 점이다. 

 

참조 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

 

Array.prototype

Array 인스턴스는 Array.prototype을 상속받습니다. 다른 모든 생성자처럼, 생성자의 프로토타입을 변경해 모든Array 인스턴스를 일괄적으로 바꿀 수 있습니다. 예컨대 모든 Array 객체에 새로운 속성과 메서드를 추가할 수 있습니다. 폴리필은 이런 점을 이용합니다.

developer.mozilla.org

 

3.Array-Like objects

Array-Like objects 는 배열과 같이 보이지만 실제 배열은 아니다.
이것은 다양한 번호가 매겨진 요소와 length 속성을 가지고 있다. 
하지만 Array 의 기능이 없으며 for-in loop 가 동작하지 않는다.
일반적으로는 모든 js function 내부에 존재하는 arguments variable 이다.

HTML node 집합은 document.getElementsByTagName(), document.forms 및 기본적으로 항목을 list로 제공하는 속성과 DOM method 이다.

 

document.forms

자바스크립트에서는 form에서 사용되는 양식들을 forms 객체에서 정의할 수 있다.
forms 객체는 links, images 등과 같은 배열 형태로 document 객체의 하단에 존재하는 객체이다.

 

[TEST] 

<form> // document.forms[0]

<input type="text"> // document.forms[0].elements[0]

<input type="text"> // document.forms[0].elements[1]

</form>

<form> // document.forms[1]

<input type="text"> // document.forms[1].elements[0]

<input type="text"> // document.forms[1].elements[1]

</form>

 

[TEST]

function takesTwoParams(){ 
    // arguments is an array-like variable that is automatically created 
    // arguments.length works great 
    alert ('you gave me ' + arguments.length + ' arguments');  
    for(i=0; i< arguments.length; i++){ 
        alert('parameter ' + i + ' = ' + arguments[i]);  
    } 
}

takesTwoParams('one', 'two', 'three'); 
// alerts "you gave me 3 arguments", 
// then "parameter 0 = one"  
// etc. 

 

Array function 은 함수를 찾을 수 있는 한 non-array objects 에서도 호출할 수 있다. 

Array : 이 object는 다른 모든 array 가 해당 속성을 상속하는 original array 이다.
Array.prototype : 이를 통해 array 가 상속하는 모든 methods properties 에 접근할 수 있다.

Array.prototype.sliceprototype chain 을 통해 모든 array 에 제공되는 slice method 이다.
하지만 직접적으로 호출할 수 없다. 왜냐하면 이것이 내부적으로 실행될 때, this 키워드를 살펴보고, 여기에서 호출하면 변수가 아닌 this 지점을 지정하기 때문에 직접 호출 할 수는 없다.
Array.prototype.slice.call()call() 및 apply() 는 자바스크립트의 모든 함수에서 호출 될 수 있다는 것을 의미하는 함수 객체의 prototype method 이다. 이것은 this 변수가 가리키는 것을 주어진 함수 내부로 변경할 수 있다. 그리고 array 를 얻을 수 있다.  이것은 javascript 에서 제공하는 것이 아닌 Array 타입의 새로운 객체를 반환하기 때문에 동작한다.

 

[TEST]

function _each(list, iter) {
    for(var i = 0; i < list.length; i++) {
        iter(list[i]);
    }
    // 받은 값을 그대로 return하는 함수이다.
    return list;
}


function _map(list, mapper) {
    var new_list = [];
    _each(list, function(val) {
        new_list.push(mapper(val));
    });
    return new_list;
}

document.querySelectorAll('body') // [body]
document.querySelectorAll('*') 
// 모든 tag가 배열처럼 보여진다. 
// querySelectorAll은 객체 컬렉션인 NodeList를 반환한다.
// 하지만 이는 array 객체가 아닌 array_like 객체이다. 
// _proto_: NodeList 이다. 즉 배열이 아니다.
// 만약 배열이라면 map method가 적용될 것이다.

document.querySelectorAll('*').map(function(node) {return node.nodeName; }) //TypeError
_map(document.querySelectorAll('*'), function(node) { return node.nodeName; }) // returns __proto__: Array(0)

// map method를 함수형으로 전환하였더니 querySelectorAll에는 없었던 함수를 사용할 수 있게 되었다.
// _map 함수는 들어오는 인자가 length가 있고 0부터 (length-1)만큼 반복문이 실행되었을 때 해당하는 key마다 값이 있으면 사용이 가능하다.
// 함수형 프로그래밍에서는 함수를 먼저 만들고 함수에 맞는 데이터를 구성해서 적용하는 방식으로 프로그래밍을 하게된다.

 

[실행화면]

 

참조 : https://www.nfriedly.com/techblog/2009/06/advanced-javascript-objects-arrays-and-array-like-objects/

 

Advanced Javascript: Objects, Arrays, and Array-Like objects

 

www.nfriedly.com

참조 : https://developer.mozilla.org/ko/docs/Web/API/Document/querySelectorAll

 

Document.querySelectorAll()

Document 메소드 querySelectorAll() 는 지정된 셀렉터 그룹에 일치하는 다큐먼트의 엘리먼트 리스트를 나타내는 정적(살아 있지 않은) NodeList 를 반환합니다.

developer.mozilla.org

 

728x90
반응형

'Front-End > JavaScript' 카테고리의 다른 글

[JavaScript] forEach()  (0) 2019.05.27
[JavaScript] 함수형 프로그래밍  (0) 2019.03.27
[JavaScript] 현재시간 Timestamp 얻는 방법  (0) 2019.01.17
[JavaScript] Array Methods  (0) 2018.09.17
[JavaScript] Arrays  (0) 2018.09.16

댓글