Goorm(부트캠프)/Front-End 3회차
JAVASCRIPT(2일차)
inzero98
2025. 3. 14. 17:52
반응형
배열 기본 문법
- 개발을 하다보면 첫번째 요소, 두번째 요소처럼 순서가 있는 컬렉션이 필요할 때가 생기는데 이때 사용되는 것이 배열
// 빈 배열은 이렇게 만들 수 있어요
let arr = new Array()
let arr = [] // 권장
// 배열 선언할 때 초기값 넣어주고 시작하는 것 가능함
let name = ['lisa', 'mandoo', 'john']
// 자, 배열의 인덱스는 0부터 시작합니다.
// 배열 내 특정 요소를 얻고 싶다면
console.log(name[0]) // lisa
console.log(name[1]) // mandoo
console.log(name[2]) // john
// 배열 내 특정 요소를 수정하고 싶다면
name[2] = 'gimchi'
console.log(name)
// 새로운 요소를 배열에 추가하는 것도 가능
name[3] = 'gogi'
console.log(name)
// 배열에 담긴 요소가 몇 개인지 알아내려면
console.log(name.length)
// 배열에 객체로 들어갈 수 있음 즉, 자료형에 제약X
let arr = ['apple', 0, {name: 'lisa'}, function() {console.log(hi')}]
console.log(arr[2].name)
arr[3] // hi
Queue(큐) : 배열을 사용해 만들 수 있는 자료구조

큐에서 사용할 수 있는 주요 연산
- push : 맨 끝에 요소를 추가
let fruits = ["사과"];
fruits.push("오렌지", "배");
// ["사과", "오렌지", "배"]
alert( fruits );
- shift : 제일 앞 요소를 꺼내 제거한 후, 남아있는 요소들 앞으로 밀어줌
이렇게 하면 두번째 요소가 첫번째 요소가 된다.
let fruits = ["사과", "오렌지", "배"];
alert( fruits.shift() ); // 배열에서 "사과"를 제거하고 제거된 요소를 얼럿창에 띄웁니다.
alert( fruits ); // 오렌지,배
- unshift : 배열 앞에 요소를 추가
// unshift 활용 에시
let fruits = ["오렌지", "배"];
fruits.unshift('사과');
alert( fruits ); // 사과,오렌지,배
Stack(스택) : 한쪽 끝에 요소를 더하거나 뺄 수 있게 해주는 자료구조

스택에서 사용할 수 있는 주요 연산
- push : 요소를 스택 끝에 집어넣음
let fruits = ["사과", "오렌지"];
fruits.push("배");
alert( fruits ); // 사과,오렌지,배
- pop : 스택 끝 요소를 추출
let fruits = ["사과", "오렌지", "배"];
alert( fruits.pop() ); // 배열에서 "배"를 제거하고 제거된 요소를 얼럿창에 띄웁니다.
alert( fruits ); // 사과,오렌지
배열의 내부 동작 원리
let fruits = ["바나나"]
let arr = fruits; // 참조를 복사함(두 변수가 같은 객체를 참조)
console.log( arr === fruits ); // true
arr.push("배"); // 참조를 이용해 배열을 수정합니다.
console.log( arr ); // 바나나,배 - 요소가 두 개가 되었습니다.
console.log( fruits ); // 바나나,배 - 요소가 두 개가 되었습니다.
위 코드 실행해보면 분명 arr에 push했는데 fruits에도 요소가 추가되는 것을 볼 수 있다.
참조라는 개념을 알아야 하는데 가볍게 얘기를 하자면
let arr = fruits로 복사했을 때 복사본1을 따로 만드는 것이 아닌 fruits를 그대로 사용하고 있다는 것이다.
💡가볍게 알아두는 배열 성능 push / pop 은 빠르다. shift / unshift는 느리다. |
배열에 적용할 수 있는 순회 문법 (for...of)
let fruits = ["사과", "오렌지", "자두"];
// 배열 요소를 대상으로 반복 작업을 수행합니다.
// for..of 를 사용하면 현재 요소의 index는 얻을 수 X, only 값만 얻을 수 있음
for (let fruit of fruits) {
console.log( fruit );
}
// ⚠️ for..in 도 사용은 가능하지만 객체에 최적화되어 있으니
// 되도록 배열에서는 사용하지 마세요
length 프로퍼티의 신기한 기능 length는 배열의 길이를 알려주는 프로퍼티인데, length 값을 수동으로 감소시키면 배열이 잘리는 기능이 있다. 단, 증가시킬 경우에는 아무 일이 벌어지지 않으니 한번 잘려나간 배열을 length로 다시 늘릴 수는 없다. |
고급 배열 메서드
- splice(start, deleteCount, ...items)
기존의 배열의 요소를 제거하고 그 위치에 새로운 요소를 추가
// start: 배열에서의 시작 위치이다. start 만을 지정하면 배열의 start부터 모든 요소를 제거한다.
// deleteCount : 시작 위치(start)부터 제거할 요소의 수이다. deleteCount가 0인 경우, 아무런 요소도 제거되지 않는다. (옵션)
// items : 삭제한 위치에 추가될 요소들이다. 만약 아무런 요소도 지정하지 않을 경우, 삭제만 한다. (옵션)
const items1 = [1, 2, 3, 4];
// items[1]부터 2개의 요소를 제거하고 제거된 요소를 배열로 반환
const res1 = items1.splice(1, 2);
// splice를 쓰면 원본 배열이 변경된다.
console.log(items1); // [ 1, 4 ]
// 제거한 요소가 배열로 반환된다.
console.log(res1); // [ 2, 3 ]
const items2 = [1, 2, 3, 4];
// items[1]부터 모든 요소를 제거하고 제거된 요소를 배열로 반환
const res2 = items2.splice(1);
// 원본 배열이 변경된다.
console.log(items2); // [ 1 ]
// 제거한 요소가 배열로 반환된다.
console.log(res2); // [ 2, 3, 4 ]
- slice(start, end)
start 인덱스부터 end 인덱스까지(end는 제외) 요소를 복사 → 기존 배열은 변하지 않고 새로운 배열을 반환
// 얕은 복사본을 새로운 배열 객체로 반환해요.
// splice()와 다르게 원본 배열은 바뀌지 않습니다.
const animals = ["ant", "bison", "camel", "duck", "elephant"];
// end가 없으니 index 2번부터 끝까지 복사하겠죠
console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
// index2 부터 index4 직전인 index3 까지 복사하겠죠
console.log(animals.slice(2, 4)); // ["camel", "duck"]
// 음수가 들어가면 뒤에서부터 2번째 있는 요소부터 끝가지 복사합니다.
console.log(animals.slice(-2)); // ["duck", "elephant"]
// 이 경우에는 index1 부터 뒤에서부터 2번째 요소 직전까지 복사합니다.
console.log(animals.slice(1, -2)); // ['bison', 'camel']
- concat()
두 개 이상의 배열을 병합할 때 사용 → 기존 배열은 건드리지 않고 새로운 배열을 반환
const array1 = ["a", "b", "c"];
const array2 = ["d", "e", "f"];
const array3 = array1.concat(array2);
console.log(array1); // ['a', 'b', 'c']
console.log(array2); // ['d', 'e', 'f']
console.log(array3); // ["a", "b", "c", "d", "e", "f"]
// 3개의 배열을 연결할 수도 있어요.
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 값을 배열에 연결할 수도 있어요.
const letters = ["a", "b", "c"];
const alphaNumeric = letters.concat(1, [2, 3]);
console.log(alphaNumeric); // ['a', 'b', 'c', 1, 2, 3]
- forEach()
각 배열 요소에 대해 제공된 함수를 한번씩 실행
const array1 = ["a", "b", "c"];
array1.forEach((element) => console.log(element));
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
// 만약, 중간에 빈 요소가 있다면 건너뜀
// 아래 코드를 실행해봅시다.
const arraySparse = [1, 3, , 7];
let numCallbackRuns = 0;
arraySparse.forEach((element, index) => {
console.log({element});
console.log({index});
});
- includes(searchElement, formIndex)
배열의 항목에 특정 값이 포함되어 있는지를 판단하여 적절히 true/false를 반환
// searchElement(필수) : 찾을 값
// fronIndex(옵션) : 검색을 시작할 0 기반 인덱스
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// Expected output: true
const pets = ["cat", "dog", "bat"];
console.log(pets.includes("cat"));
// Expected output: true
console.log(pets.includes("at"));
// Expected output: false
console.log([1, 2, 3].includes(3, 1)) // true
console.log([1, 2, 3].includes(3, 2)) // true
console.log([1, 2, 3].includes(3, 3)) // false
- find()
제공된 배열에서 제공된 테스트 함수를 만족하는 첫번째 요소를 반환
(테스트 함수를 만족하는 값이 없으면 undefined가 반환)
// 주로 이 친구는 배열에 값이 존재하는지 찾아야할 경우 사용됩니다.
// 예시1
const array1 = [5, 12, 8, 130, 44];
// 10보다 큰 요소를 발견하면 그 요소를 반환하면서 반복문이 끝남
const found = array1.find((element) => element > 10);
console.log(found); // 12
// 예시2
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
function isCherries(fruit) {
return fruit.name === "cherries";
}
console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
- filter()
주어진 배열에서 제공된 함수에 의해 구현된 테스트를 통과한 요소들만 필터링하여 새로운 배열을 반환
const words = ["spray", "elite", "exuberant", "destruction", "present"];
const result = words.filter((word) => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
- map(callbackFunc)
호출한 배열의 모든 요소에 주어진 함수를 호출한 결과를 채운 새로운 배열을 생성
// callbackFunc = (currentValue, index, array) => {}
// currentValue : 배열 내에서 처리할 현재 요소
// index : 배열 내에서 처리할 현재 요소의 인덱스
// array : map()을 호출한 배열
const array1 = [1, 4, 9, 16];
// Pass a function to map
const map1 = array1.map((x) => x * 2);
console.log(map1);
// Expected output: Array [2, 8, 18, 32]
// 배열 속 객체를 재구성할 수도 있어요.
const kvArray = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 },
];
// currentValue가 객체여서 구조분해할당을 사용하여 직접적으로 객체 요소안의 키 값으로 접근 가능함
const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));
console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]
console.log(kvArray);
- reduce(callback, initialValue)
배열의 각 요소에 대해 주어진 리듀서 함수를 실행하고 하나의 결과값을 반환
// callback : 배열의 각 요소에 대해 실행할 함수
// callback : (accumulator, currentValue, currentIndex(option), array(option)) => {}
// accumulator : 콜백의 반환값을 누적합니다, 콜백함수의 첫 번쨰 호출이기도 해서 initialValue가 있다면 initialValue값부터 시작합니다.
// currentValue : 처리할 현재 요소
// currentIndex : 처리할 현재 요소의 인덱스, initialValue 있다면 0부터, 없다면 1부터 시작함
// array : reduce를 호출한 배열
// initialValue(옵션) : 초기값
// ex1
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue,
);
console.log(sumWithInitial);
// Expected output: 10
반응형