[Javascript]01-4. 배열

Elen li·2021년 10월 26일
0
post-thumbnail

배열

  • 크기를 지정하지 않아도 됩니다.
  • 어떤 위치에 어느 타입의 데이터를 저장하더라도 에러가 나지 않습니다.

배열 리터럴

  • 대괄호([])를 사용해 새로운 배열을 생성합니다.
  • 배열 내 위치 인덱스 값을 넣어 원하는 값에 접근합니다.
var colorArr = ['orange', 'yellow', 'blue', 'green', 'red'];

console.log(colorArr[0]);
console.log(colorArr[1]);
console.log(colorArr[4]);

// 출력값
orange
yellow
red

배열의 요소 생성

  • 배열도 객체와 마찬가지로 동적으로 배열 원소를 추가할 수 있습니다.
  • 값을 순차적으로 넣을 필요 없이, 아무 인덱스 위치에나 값을 동적으로 추가할 수 있습니다.
  • 배열의 크기는 현재 배열의 인덱스 중 가장 큰 값을 기준으로 정합니다.
// 빈 배열
var emptyArr = [];
console.log(emptyArr[0]);

// 배열 요소 동적 생성
emptyArr[0] = 100;
emptyArr[3] = 'eight';
emptyArr[7] = true;

console.log(emptyArr);

console.log(emptyArr.length);

// 출력값
undefined
[ 100, <2 empty items>, 'eight', <3 empty items>, true ]
8

배열의 length 프로퍼티

  • 자바스크립트의 모든 배열은 length 프로퍼티가 있습니다.
  • 실제로 배열에 존재하는 원소의 개수와 일치하는 것은 아닙니다.
  • length 프로퍼티 = 배열 내 가장 큰 인덱스 + 1
  • length를 명시적으로 변경할 때, 현재 인덱스보다 벗어나는 적은 값으로 입력하면 벗어난 실제 값은 삭제됩니다. (코드에서 마지막 console 출력값 확인)
// 배열 lenght 프로퍼티의 명시적 변경
var arr = [0, 1, 2];
console.log(arr.length) // (출력값) 3

arr.length = 5;
console.log(arr) // (출력값) [0, 1, 2, undefined x 2]

arr.length = 2;
console.log(arr); // (출력값) [0, 1]
console.log(arr[2]); // (출력값) undefined

배열 표준 메서드와 length 프로퍼티

  • push(): 인수로 넘어온 항목을 배열의 끝에 추가합니다.
  • 배열의 length 프로퍼티는 배열 메서드 동작에 영향을 줄 수 있는만큼 배열에서는 중요한 프로퍼티입니다.
// push() 메서드와 length 프로퍼티
// arr 배열 생성
var arr = ['zero', 'one', 'two'];

// push() 메서드 호출
arr.push('three');
console.log(arr); // (출력값) ['zero', 'one', 'two', 'three']

// length 값 변경 후, push() 메서드 호출
arr.length = 5;
arr.push('four');
console.log(arr); // (출력값) ['zero', 'one', 'two', 'three', undefined, 'four']

배열과 객체

  • 자바스크립트 엔진은 [] 연산자 내에 숫자가 사용될 경우, 자동으로 문자열로 바꿔줍니다.
    • 아래 코드에서 colorsArray와 비슷한 방식으로 colorObj를 리터럴 방식으로 객체를 생성합니 다.
    • 프로퍼티의 속성은 문자열 형태여야 하므로 colorsObj는 (‘0’, ‘1’, ’2’)의 형태로 넣어줍니다
    • 각 원소의 값에 접근하기 위해서 인덱스를 넣어줘도 결과가 동일하게 나오늘 것을 확인할 수 있습니다.
// colorsArray 배열
var colorsArray = ['orange', 'yellow', 'green'];
console.log(colorsArray[0]);
console.log(colorsArray[1]);
console.log(colorsArray[2]);

// colorsObj객체
var colorsObj = {
  '0' : 'orange', 
  '1' : 'yellow',
  '2' : 'green'
};

console.log(colorsObj[0]);
console.log(colorsObj[1]);
console.log(colorsObj[2]);

// 출력값
orange
yellow
green
orange
yellow
green
  • 자바스크립트에서 배열은 객체타입으로 인식합니다.
    • 아래 코드처럼 확인하면 배열과 리터럴 객체의 타입 결과가 모두 object 인 것을 확인할 수 있습니다.
// colorsArray 배열
var colorsArray = ['orange', 'yellow', 'green'];

// colorsObj객체
var colorsObj = {
  '0' : 'orange', 
  '1' : 'yellow',
  '2' : 'green'
};


// typeof 연산자 비교
console.log(typeof colorsArray);
console.log(typeof colorsObj);

// 출력값
object
object
  • 객체로 만든 배열에서는 ‘.length’ ‘push’ 와 같은 메서드를 사용할 수 없습니다.
    이는 객체로 만든 배열과 대괄호를 사용해 만든 배열의 프로토타입이 다르기 때문입니다.
    • 객체로 만든 배열의 프로토타입 = Object
    • [] 배열의 프로토타입 = Array
var emptyArray = [];
var emptyObj = {};

console.dir(emptyArray.__proto__);
console.dir(emptyObj.__proto__);

// 출력값
배열의 프로토타입 (Array.prototype) 출력
객체의 프로토타입 (Object.prototype) 출력

배열의 프로퍼티 동적 생성

  • 배열도 객체이므로, 인덱스가 숫자인 배열 원소 이외에도 객체처럼 동적으로 프로퍼티를 추가할 수 있습니다.

//프로퍼티 동적 추가
arr.color = 'blue';
arr.name = 'jasper';
arr.age = 30;
console.log(arr);

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

// 배열 객체 출력 (크롬 개발자도구)
console.dir(arr);

// 출력값
0: ‘zero’
1: ‘one’
2: ‘two’
3: ‘red’
color: ‘blue’
name: ‘jasper’

배열의 프로퍼티 열거

  • 배열도 객체이므로 ‘for in’문을 사용해서 모든 프로퍼티를 열거할 수 있습니다.
  • 하지만 불필요한 프로퍼티가 출력될 수 있도록 for문을 사용하는 것이 좋습니다.
for (var prop in arr) {
  console.log(prop, arr[prop]);
}

// 출력값
0 ‘zero’
1 ‘one’
2 ‘two’
3 ‘red’
color ‘blue’
name ‘jasper’


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

// 출력값
0 ‘zero’
1 ‘one’
2 ‘two’
3 ‘red’

배열 요소 삭제

  • 배열도 객체이므로 ‘delete’ 연산자를 이용할 수 있습니다.
  • delete 연산자는 해당 요소의 값을 undefined로 설정할 뿐 원소 자체를 삭제하지 않습니다.
  • 요소를 완전히 제거할 때에는 splice() 메서드를 사용합니다.
// delete 연산자를 이용한 배열 프로퍼티 삭제
var arr = ['zero', 'one', 'two', 'three'];
delete arr[2];
console.log(arr);
console.log(arr.length);

// 출력값
['zero', 'one', undefined, 'three']
4

// splice() 메서드를 이용한 배열 프로퍼티 삭제
arr.splice(2, 1);
console.log(arr);
console.log(arr.length);

// 출력값
[“zero”, “one”, “three”]
3

Array() 생성자 함수

  • 배열 리터럴은 자바스크립트 기본 제공 Array() 생성자 함수로 배열 생성하는 과정을 단순화시킨 것입니다.
  • 생성자 함수로 배열같은 객체를 생성할 때에는 반드시 new 연산자를 같이 써야합니다.
  • Array() 생성자 함수는 호출할 때 인자 개수에 따라 동작이 다르므로 주의해야 합니다.
    • 호출할 인자 1개 (숫자): 호출된 인자를 length로 갖는 빈 배열 생성
    • 그 외의 경우: 호출된 인자를 요소로 갖는 배열 생성
// Array() 생성자 함수를 통한 배열 생성
var foo = new Array(3);
console.log(foo); // (출력값) [undefined, undefined, undefined]
console.log(foo.length); // (출력값) 3

var bar = new Array(1, 2, 3);
console.log(bar); // (출력값) [1, 2, 3]
console.log(bar.length); // (출력값) 3

유사 배열 객체 (array-like objects)

  • 일반 객체에 length라는 프로퍼티를 갖고 있는 경우를 의미합니다.
  • 유사 배열 객체는 객체임에도 불구하고, 자바스크립트의 표준 배열 메서드를 사용하는게 가능합니다.
//유사 배열 객체의 배열 메서드 호출
var arr = ['bar'];
var obj = {
  name : 'foo',
  length: 1
};

arr.push('baz');
console.log(arr);

// obj.push('baz');
Array.prototype.push.apply(obj, ['baz']);
console.log(obj);

// 출력값
[‘bar’, ‘baz]
[1: ‘baz’, name : foo, length: 2]
profile
Android, Flutter 앱 개발자입니다.

0개의 댓글