Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

보근은 참고 있다

JS의 배열 본문

Language/JS

JS의 배열

보근 2021. 8. 6. 16:35

 

 

 

 

 

 

 

 

 

배열은 특별한 형태의 객체이다. C나 Java의 배열과 기능은 비슷하지만, 크기가 가변적이며, 어떤 위치에 어떤 데이터 타입을 저장해도 에러가 생기지 않는다.

 

 

 

 

배열의 생성

  • 배열 리터럴
    객체의 중괄호처럼 배열의 리터럴은 대괄호 ( [ ] )를 이용하여 생성한다.
  • 생성자 함수
    new Array() 생성자 함수를 통해서 배열을 생성한다.
var array1 = new Array();			// 빈 배열 생성.

console.log(array1);				// []
console.log(array1.length);			// 0

var array2 = new Array(3);			// 길이가 3인 빈 배열 생성.

console.log(array2);				// [undefined, undefined, undefined]
console.log(array2.length);			// 3

var array3 = new Array(1, 2, 3);	// 1, 2, 3이 차례대로 들어간 배열 생성.

console.log(array3);				// [1, 2, 3]
console.log(array3.length);			// 3

생성자 함수를 통해 배열을 만드는 예시.

 

 

 

 

var array1 = [];							// 빈 배열을 생성.
var array2 = [1, "2", {value: 3}, [4]];		// 4개의 요소가 담긴 배열 생성.

console.log(array1.length);					// 배열의 길이는 0.

array1[0] = 1;
array1[1] = "2";
array1[2] = {value: 3};
array1[3] = [4];

console.log(array1[0]);						// 1
console.log(array1[1]);						// "2"
console.log(array1[2]);						// {value: 3}
console.log(array1[3]);						// [4]
console.log(array2[0]);						// 1
console.log(array2[1]);						// "2"
console.log(array2[2]);						// {value: 3}
console.log(array2[3]);						// [4]

console.log(array1.length);					// 배열의 길이 4.

array1[9] = 0;								// 9번 인덱스에 요소를 추가.

console.log(array1.length);					// 배열의 길이 10.

 

위의 예제에서 볼 수 있듯이, 배열도 객체처럼 요소를 동적으로 추가할 수 있다.

 

그리고, 배열의 프로퍼티 중에 length가 있는데 이 값은 배열의 길이를 나타내는 값이다. 위의 예시처럼 9번 인덱스에 값을 추가하면 배열의 length가 10이 된다. 값을 할당받지 못한 배열의 인덱스는 당연히 undefined로 값이 표시된다.

 

var array = [1, 2, 3];	// array.length = 3

array[5] = 0;			// array.length = 6

// 배열의 값을 undefined로.
array[5] = undefined;	// array.length = 6

// 배열의 length 값을 3으로.
array[5] = 0;
array.length = 3;		// array.length = 3

console.log(array[5]);	// undefined

그리고 이거는 호기심에 해본 건데 배열의 길이보다 큰 인덱스에 값을 할당하는 것이 배열의 길이를 변경시켰는데, 마지막 인덱스 값을 undefined로 해도 배열의 길이는 변하지 않았다.

반대로, 배열의 길이를 줄이니 길이보다 큰 배열의 값들은 다 없어져 버렸다.

 

 

 

 

 

 

 

배열과 객체

배열은 객체이지만, 그냥 일반 객체와는 다르다.

 

var array = [ 'red', 'green', 'blue'];
var object = {
    '0': 'red',
    '1': 'green',
    '2': 'blue'
};

console.log(array[0]);		// red
console.log(array[1]);		// green
console.log(array[2]);		// blue

console.log(object[0]);		// red
console.log(object[1]);		// green
console.log(object[2]);		// blue

console.log(typeof array);	// object
console.log(typeof object);	// object

console.log(array.length);	// 3
console.log(object.length);	// undefined

배열 array와 일반 객체 object를 같은 모양으로 만들었다.

 

객체의 프로퍼티에 대괄호로 접근할 경우 프로퍼티 이름을 문자열로 기입하여야 하지만, 숫자의 경우 엔진이 자동으로 문자열로 바꿔주기 때문에 둘이 같은 모양으로 사용할 수 있다.

 

배열 역시 객체이기 때문에 typeof 연산자를 사용하면 object라는 결과를 반환한다.

 

하지만, 일반 객체인 object는 배열의 프로퍼티를 사용할 수 없다는 다른점이 있다. 

 

출처 : https://codedragon.tistory.com/5714

위의 그림은 일반 객체와 배열 객체의 프로토타입을 보여준다.

 

console.dir(array.__proto__);				// Array
console.dir(object.__proto__);				// Object
console.dir(array.__proto__.__proto__);			// Object

console.log(object.__proto__ === array.__proto__.__proto__);	// true

위의 예시로 위위 그림을 확인할 수 있다.

 

 

 

 

 

 

배열의 프로퍼티

배열도 객체이므로 인덱스로 접근하는 배열 요소 외에도 프로퍼티를 가질 수 있다.

 

var array = ['one', 'two', 'three'];

console.log(array.length);		// 3

array.one = 1;					// 배열의 프로퍼티 동적 생성

console.log(array.one);			// 1
console.log(array.length);		// 3 length 값이 변하지 않음

array[3] = 2;					// 배열의 요소 추가

console.log(array[3]);			// 2
console.log(array.length);		// 4 length 값이 변함

console.dir()를 통해서 추가된 프로퍼티 one을 확인할 수 있다.

 

 

 

 

배열도 객체니까 for in문을 사용할 수 있는데, 위의 예시처럼 프로퍼티를 갖고 있는 배열 객체라면 요소와 그 프로퍼티의 값들도 반환될 것이다. 배열 요소만을 출력하고 싶다면, 그냥 for문을 쓰면 된다.

 

var array = ['one', 'two', 'three'];
array.hello = 'haha';
array.bye = 'baba';

for(var property in array) {
    console.log(array[property]);
}

console.log('----------------------');

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


// result

one
two
three
haha
baba
----------------------
one
two
three

 

 

 

 

 

배열 요소의 삭제

배열도 객체이기 때문에, delete 연산자를 사용할 수 있다.

var array = ['one', 'two', 'three'];

console.log(array.length);	// 3

delete array[2];			// 3번째 요소를 delete

console.log(array[2]);		// undefined
console.log(array.length);	// 3

배열의 마지막 요소를 delete 했지만, 마지막 요소가 undefined가 됐을 뿐 length가 줄어들지는 않았다. 배열의 메서드들은 length 값으로 동작하는 경우가 많기 때문에, 마지막 요소가 없어진 것처럼 배열이 동작하길 원할 때는 배열의 메서드인 splice()를 사용한다.

 

 

var array = ['one', 'two', 'three', 'four'];

array.splice(2, 1);			// 배열의 2번 인덱스부터 1개 삭제
console.log(array);			// ['one', 'two', 'four']
console.log(array.length);		// 3

 

 

 

 

 

유사 배열 객체

배열의 메서드들은 대부분 length를 이용해 동작하는 경우가 많기 때문에, 배열의 length 프로퍼티는 매우 중요하다.

JS에서 일반 객체에 length 프로퍼티를 추가한 것을 유사 배열 객체라고 한다. 이 것의 특별한 점은 일반 객체임에도 불구하고, 배열의 표준 메서드를 사용할 수 있다는 것이다.

 

var array = ['one', 'two'];
var object = {
    name: 'bogeun',
    age: 20,
    length: 3
}

array.push('three');			// 배열 요소에 'three' 추가
console.log(array);				// ['one', 'two', 'three']
console.log(array.length);		// 3

// object.push('hello');		// 에러 뜸.

console.log(object);			// {name: 'bogeun', age: 20, length: 3}
Array.prototype.push.apply(object, ['hello']);		// apply()
console.log(object);			// {'3': 'hello', name: 'bogeun', age: 20, length: 4}

그냥 배열 메서드를 사용하려고 하면 object에는 push라는 메서드가 없다고 에러가 뜬다. 하지만 apply()를 사용하면 length에 따라 3번 인덱스에 요소가 추가되고, length가 3에서 4로 값이 변한다. 배열의 push() 메서드를 정확히 수행한다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Language > JS' 카테고리의 다른 글

함수 호출과 this  (0) 2021.08.20
JS의 함수  (0) 2021.08.16
JS 데이터 타입과 연산자  (0) 2021.08.04
Comments