본문 바로가기

Language & Framework/JavaScript

자바스크립트 기초. Array (배열) (1)

Array ?

1) 연관된 내용을 그룹핑하여 하나의 변수로 모아서 관리하는 것이 배열이다.

2) 하나의 인덱스에 한 개의 값이 저장된 순차적 자료구조의 형태를 띄고 있다.

3) 인덱스는 0부터 시작한다.

 

1. Array decalaration 배열 선언

const cafe1 = new Array("starbucks", "twosome");
const cafe2 = ["starbucks", "twesome"];

console.log(cafe1); // (2) ['starbucks', 'twosome']
console.log(cafe2); // (2) ['starbucks', 'twosome']

 

변수명에 바로 선언할 경우에는 대괄호를 사용하고 new 연산자를 사용할 경우에는 소괄호를 사용할 수 있다.

그러나 찾아본 결과 new 연산자();는 되도록 사용하지 않고 변수명 = []형태의 선언 방식을 사용하는 것이 좋다고 한다.

설명하려면 너무 길어지는 내용이기도 하고 나 같은 초보가 이야기할 것은 아니니 여기서 참고하길 바란다.

 

 

2. index position 인덱스 위치

const weapon = ["gun", "knife", "fist"];
console.log(weapon.length); //3
console.log(weapon); //Array(3)
console.log(weapon[0]); //gun
console.log(weapon[1]); //knife
console.log(weapon[2]); //fist
console.log(weapon[3]); //undefined 
console.log(weapon[weapon.length - 1]); //fist

 

배열의 인덱스는 0부터 시작이며 존재하지 않는 인덱스를 호출할 경우 undefined를 반환한다.

또한 굉~장히 긴 배열의 가장 마지막 인덱스를 선택하고 싶다면 [인덱스명.length - 1]을 입력해주면 된다.

 

 

3. Loop array 배열 반복문

일단 지금까지 배운 기본적인 문법을 이용해서 배열을 반복 호출해보자.

const Classmate = ["또띠", "띵또", "뚱땅", "땡똥"];
for (let i = 0; i < Classmate.length; i++) {
  console.log(Classmate[i]); // 또띠 -> 띵또 -> 뚱땅 -> 땡동 순으로 순차적 반환
} 

for (let classmate of Classmate) {
  console.log(classmate); // 또띠 -> 띵도 -> 뚱땅 -> 땡동 순으로 순차적 반환
}

첫번째 예시는 설명할 것도 없이 간단한 예제고 두번째 예시는 for in의 경우 객체 순환, for of은 배열 순환에 사용된다는 것을 지난 시간에 배웠다!

이번엔 forEach라는 API를 사용해서 배열 반복문을 만들어보자.

     * Performs the specified action for each element in an array.
     * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
     * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
    forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;

forEach를 + click하면 나오는 정보. (Windows는 control + click)

자세하게 알면 좋지만 아직 읽어도 무슨 말인지 잘 모르니까 예제를 보고 바로 대입해보도록 하자.

 

Classmate.forEach(function (classmate, index, array) {
  console.log(classmate, index, array);
});
//또띠 0 (4) ['또띠', '띵또', '뚱땅', '땡똥']
//띵또 1 (4) ['또띠', '띵또', '뚱땅', '땡똥']
//뚱땅 2 (4) ['또띠', '띵또', '뚱땅', '땡똥']
//땡똥 3 (4) ['또띠', '띵또', '뚱땅', '땡똥']

위의 내용을 그대로 대입했더니 값과 인덱스 번호, 그리고 배열이 전부 다 4번 반복되고 있다.

우리가 필요한 건 Value 뿐이니 index와 array는 없에버리도록 하자. 그리고 무기명 함수인 function은 생력할 수 있으며, 대괄호 또한 Arrow로 생략 가능하다.

그럼 아래와 같은 형태가 된다. 배열 반복문은 여기서 끝.

Classmate.forEach((classmate) => console.log(classmate));
// 또띠 띵똥 뚱땅 땡똥 순차 반환

 

 

4. Addition, deletion 배열에 값 추가하거나 제하기

자바스크립트의 내장 API를 이용해서 배열의 값을 추가하거나 제거할 수 있다.

push 배열의 제일 뒤에 값을 추가한다.
pop 배열의 제일 뒤에 위치한 값을 제거한다.
shift 배열의 제일 앞에 위치한 값을 제거한다.
unshift 배열의 제일 앞에 값을 추가한다.
splice(index number, delete count) 원하는 부분의 값을 제거하고 원하는 값을 추가한다. 

*** Shift, Unshift는 배열 전체의 인덱스 값을 수정해줘야 하기 때문에 배열이 길어질 수록 시스템에 부담을 준다. 따라서 되도록 pop, push 혹은 slice를 사용하는 것이 좋다.

 

어려울 것은 없으니 바로 실전에서 사용해보도록 하자.

 

const animal = ["lion", "dog", "mouse", "ddoddi"];
animal.push("eagle", "cat");
console.log(animal); // ['lion', 'dog', 'mouse', 'ddoddi', 'eagle', 'cat']

animal.pop();
animal.pop();
console.log(animal); // ['lion', 'dog', 'mouse', 'ddoddi']

animal.unshift("mammoth", "duck");
console.log(animal); //['mammoth', 'duck', 'lion', 'dog', 'mouse', 'ddoddi']

animal.shift();
animal.shift();
console.log(animal); //['lion', 'dog', 'mouse', 'ddoddi']

animal.splice(1, 2);
console.log(animal); //['lion', 'ddoddi']

animal.splice(1, 0, "dog", "mouse");
console.log(animal); //['lion', 'dog', 'mouse', 'ddoddi']

다른 건 굉장히 쉽지만 splice는 헷갈릴 수 있으니 한 번만 짚고 넘어가자.

splice에서 첫번째 숫자는 지정할 index number를 의미하고 두번째 숫자는 index number로부터 몇 개를 지울 건지에 대한 countd이다.

따라서 지우고 싶은 생각이 없고 값을 넣기만 하고 싶다면 넣고 싶은 위치와 0을 입력하면 된다.

 

그리고 두 개 이상의 배열을 합칠 수 있는 API도 있다.

아래 코드 블럭의 concat을 활용하면 된다.

  concat(...items: ConcatArray<T>[]): T[];
    /**
     * Combines two or more arrays.
     * This method returns a new array without modifying any existing arrays.
     * @param items Additional arrays and/or items to add to the end of the array.
     * 두 개 혹은 그 이상의 배열을 결합한다.
     * 이 방법은 새로운 배열을 반환하며 기존 배열을 수정하지 않는다.
     * @파라미터 item에 배열을 추가 (그리고/또는) item을 추가한다 배열의 끝에.
     **/
     
const concatpractice = ddoddi.concat(animal);
console.log(concatpractice);
// [1, 2, 3, 4, 5, 'lion', 'dog', 'mouse', 'ddoddi']

 

 

5. Searching ( 특정 값의 인덱스 찾기 )

 

const animal2 = ["lion", "dog", "mouse", "ddoddi", "dog"];
console.log(animal2.indexOf("dog")); // 1
console.log(animal2.lastIndexOf("dog")); // 4

단순한 API라 딱히 설명할 건 없지만 중요한 건 || (or 연산자)나 && (AND연산자) 처럼 해당 값을 만나면 바로 반환하기 때문에 같은 값이 두개가 존재할 시 indexOf의 경우 인덱스 0부터 읽다가 해당 값을 만나면 바로 반환하며 lastIndexOf의 경우 인덱스의 마지막부터 거꾸로 읽다가 해당 값을 만나면 바로 반환한다.