TIL 5 - JavaScript (Array)

chachacha·2021년 3월 31일
0

JavaScript

목록 보기
4/8
post-thumbnail

Array(배열)란?

개발을 진행하다 보면 순서가 있는 collection이 필요할 때가 있습니다. 이런 경우 객체를 사용하면 순서와 관련된 method가 없어 불편할때가 많습니다 왜냐하면 객체는 순서를 고려하지 않고 만들어진 자료구조이기 때문입니다.

이럴 땐 순서가 있는 컬렉션을 저장할 때 쓰는 자료구조인 배열을 써줍시다!

배열 선언하는 방법 😁

빈 배열을 만드는 문법입니다.

let arr = new Array();  // method 1
let arr = [];           // method 2

보통 method 2로 배열을 선언합니다 그리고 대괄호 안에 초기 요소를 input하는 것도 가능합니다.

let desserts = ["ice cream", "cake", "pie"];

그리고 각 배열 요소엔 0부터 시작하는 숫자(index)가 매겨져 있습니다.

let desserts = ["ice cream", "cake", "pie"];
alert(desserts[0]);  // ice cream
alert(desserts[1]);  // cake
alert(desserts[2]);  // pie

요소를 수정할 수도 있습니다.

// array changes to ["ice cream", "chocolate", "pie"]
desserts[1] = 'chocolate';  

새로운 요소를 배열에 추가 할수도 있습니다.

// array changes to ["ice cream", "chocolate", "pie", "cookie"]
desserts[3] = "cookie";

length를 사용하면 배열에 담긴 요소가 몇 개인지 알 수 있습니다.

let desserts = ["ice cream", "cake", "pie"];
alert(desserts.length);  // 3

배열 요소의 자료형엔 제약이 없다!

// there are different data types in array
let arr = ['coke', {name:'Chris'}, true, function () {alert('Hello!');}];
// prints name property which has index of 1
alert(arr[1].name);  // Chris
arr[3]();  // Hello!

pop/push and shift/unshift

Queue는 배열을 사용해 만들 수 있는 대표적인 자료구조이고, 순서가 있는 collection을 저장하는 데 사용합니다. (Always remember FIFO✌️)

Queue에서 사용하는 주요 연산!
push - 맨 끝에 요소를 추가 함.
shift - 제일 앞 요소를 꺼내 제거한 후 남아있는 요소들을 앞으로 밀어줌.

Stack이라는 자료구조를 구현할 때도 배열을 쓰게 됩니다. (Always remember LIFO✌️)

Stack에서 사용하는 주요 연산!
push - 요소를 스택 끝에 집어넣음.
pop - 스택 끝 요소를 추출함.

pop - Example (배열 끝 요소를 제거하고, 제거한 요소를 반환함.)

let fruits = ['apple', 'orange', 'pear'];
alert(fruits.pop());  // 'pear' is taken out of the array.
alert(fruits);  // apple, orange

push - Example (배열 끝에 요소를 추가함.)

let fruits = ['apple', 'orange'];
fruits.push('pear');
alert(fruits);  // apple, orange, pear

shift - Example (배열 앞 요소를 제거하고, 제거한 요소를 반환함.)

let fruits = ['apple', 'orange', 'pear'];
alert(fruit.shift());  // takes apple out of the array.
alert(fruit);  // orange, pear

unshift - Example (배열 앞에 요소를 추가함.)

let fruits = ['orange', 'pear'];
fruits.unshift('apple');
alert(fruits); // apple, orange, pear

pushunshift는 요소 여러 개를 한 번에 더해줄 수 있음.

let fruits = ['apple'];
fruits.push('orange', 'pear');
fruits.push('pine apple', 'lemon');
// ['pine apple', 'lemon', 'apple', 'orange', 'pear']
alert(fruits);

Reference
https://ko.javascript.info/array

0개의 댓글