[마스터 개념] 3 | 배열
1 variable 변수
2 operator 연산자
3 function 함수
4 object 객체
5 class 클래스
7 built-in 빌트인 객체
8> array 배열
9 iterator 이터러블
10 map
11 more-operators 유용한 연산자들
12 module 모듈
13 promise 프로미스
14 scope 스코프
15 prototype 프로토타입
16 closure 클로져
17 this
8 array 배열
일반적인 배열은 동일한 메모리 크기, 연속적, 자바스크립트의 배열은 동일한 메모리 크기를 가지지 않고, 연속적으로 이어져 있지 않다.
오브젝트와 유사하며 일반적인 배열의 동작을 흉내 낸 특수한 객체이다. 자바스크립트 배열은 다른 타입의 데이터를 넣을 수 있으므로 타입이 정해져 있는 타입배열(Typed Collections)이 있다.
let array = new Array(3);
console.log(array); // [ <3 empty items> ]
array = new Array(1, 2, 3);
console.log(array); // [ 1, 2, 3 ]
array = Array.of(1, 2, 3, 4, 5);
console.log(array); // [ 1, 2, 3, 4, 5 ]
const array2 = [1, 2, 3, 4];
console.log(array2); // [ 1, 2, 3, 4 ]
array = Array.from(array2);
console.log(array); // [ 1, 2, 3, 4 ]
array = Array.from({
0: "안",
1: "녕",
length: 2,
});
console.log(array); // [ '안', '녕' ]
from( ) : iterable 객체를 받아 기존의 배열로 새로운 배열을 반환
오브젝트에 인덱스 키와 length 키를 작성하면 배열로 만들 수 있다.
add
const fruits = ["바나나", "사과", "포도", "복숭아"];
// 인덱스로 바로 접근하면 안좋음
fruits[6] = "딸기";
console.log(fruits); // [ '바나나', '사과', '포도', '복숭아', <2 empty items>, '딸기' ]
// delete를 사용하면 그 자리가 비어있어서 안좋음
delete fruits[1];
console.log(fruits); // [ '바나나', <1 empty item>, '포도', '복숭아', <2 empty items>, '딸기' ]
array-method
const fruits = ["바나나", "사과", "포도", "복숭아"];
// 특정한 오브젝트가 배열인지 체크
console.log(Array.isArray(fruits)); // true
console.log(Array.isArray({})); // false
// 특정한 아이템의 위치를 찾을 때
console.log(fruits.indexOf("사과")); // 1
// 배열 안에 특정한 아이템이 있는지 체크
console.log(fruits.includes("사과")); // true
const fruits = ["바나나", "사과", "포도", "복숭아"];
// > 배열 자체를 수정 (업데이트)
// 추가 - 맨 뒤
let length = fruits.push("수박"); // 길이를 리턴
console.log(fruits); // [ '바나나', '사과', '포도', '복숭아', '수박' ]
console.log(length); // 5
// > 배열 자체를 수정 (업데이트)
// 추가 - 맨 앞
length = fruits.unshift("딸기"); // 길이를 리턴
console.log(fruits); // [ '딸기', '바나나', '사과', '포도', '복숭아', '수박' ]
console.log(length); // 6
// > 배열 자체를 수정 (업데이트)
// 제거 - 맨 뒤
let lastItem = fruits.pop(); // 제거된 아이템 리턴
console.log(fruits); // [ '딸기', '바나나', '사과', '포도', '복숭아' ]
console.log(lastItem); // 수박
// > 배열 자체를 수정 (업데이트)
// 제거 - 맨 앞
lastItem = fruits.shift(); // 제거된 아이템 리턴
console.log(fruits); // [ '바나나', '사과', '포도', '복숭아' ]
console.log(lastItem); // 딸기
// > 배열 자체를 수정 (업데이트)
// 중간에 삭제 splice(해당 인덱스부터, 삭제할 개수)
const deleted = fruits.splice(1, 1); // 제거된 아이템 배열 형태로 리턴
console.log(fruits); // [ '바나나', '포도', '복숭아' ]
console.log(deleted); // [ '사과' ]
// 중간에 추가 splice(해당 인덱스부터, 삭제할 개수, '추가1', '추가2', ...)
fruits.splice(1, 0, "사과", "딸기");
console.log(fruits); // [ '바나나', '사과', '딸기', '포도', '복숭아' ]
// > 기존 배열 수정 X, 새로운 배열 만듦 (새로운)
// 잘라진 새로운 배열을 만듦 slice(해당 인덱스부터, 해당 인덱스 전까지)
let newArr = fruits.slice(0, 2); // 잘라진 새로운 배열 리턴
console.log(newArr); // [ '바나나', '사과' ]
console.log(fruits); // [ '바나나', '사과', '딸기', '포도', '복숭아' ]
newArr = fruits.slice(-1);
console.log(newArr); // [ '복숭아' ]
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// > 기존 배열 수정 X, 새로운 배열 만듦 (새로운)
// 여러 배열 이어줌
const arr3 = arr1.concat(arr2); // 이어진 새로운 배열 리턴
console.log(arr1); // [ 1, 2, 3 ]
console.log(arr2); // [ 4, 5, 6 ]
console.log(arr3); // [ 1, 2, 3, 4, 5, 6 ]
// > 기존 배열 수정 X, 새로운 배열 만듦 (새로운)
// 순서를 거꾸로
const arr4 = arr3.reverse(); // 거꾸로된 새로운 배열 리턴
console.log(arr4); // [ 6, 5, 4, 3, 2, 1 ]
// > 기존 배열 수정 X, 새로운 배열 만듦 (새로운)
// 중첩 배열을 하나의 배열로 쫙 펴기
let arr = [
[1, 2, 3],
[4, [5, 6]],
];
console.log(arr); // [ [ 1, 2, 3 ], [ 4, [ 5, 6 ] ] ]
// 1 단계까지만 플랫을 해줌 (기본값)
console.log(arr.flat()); // [ 1, 2, 3, 4, [ 5, 6 ] ]
console.log(arr.flat(2)); // [ 1, 2, 3, 4, 5, 6 ]
// > 배열 자체를 수정 (업데이트)
// 특정한 값으로 배열 채우기 fill('해당 문자열을', 해당 인덱스부터, 해당 인덱스 전까지)
arr.fill(0);
console.log(arr); // [ 0, 0, 0, 0, 0, 0 ]
arr.fill("s", 1, 3);
console.log(arr); // [ 0, 's', 's', 0, 0, 0 ]
arr.fill("a", 1);
console.log(arr); // [ 0, 'a', 'a', 'a', 'a', 'a' ]
// > 배열 자체를 수정 (업데이트)
// 배열을 문자열로 합하기 join('해당 문자열로')
let text = arr.join(); // (,) 기본값
console.log(text); // 0,a,a,a,a,a
text = arr.join(" | ");
console.log(text); // 0 | a | a | a | a | a
shalllow 얕은 복사
자바스크립트에서는 항상 얕은 복사가 이뤄지는데 얕은 복사는 객체의 메모리 주소가 전달된다.
ex) Array.from, concat, slice, spread(...), Object assign
higher-order-function 고차함수
인자로 함수를 받거나 (콜백함수) 함수를 반환하는 함수를 고차함수라고 한다.
순수함수 : 데이터 변경 X, 변수 X, 조건문 X, 반복문 X => 에러 낮추고, 가독성 높임
순수함수들을 엮어 함수형 프로그래밍으로 만든다.
const fruits = ["바나나", "딸기", "포도", "딸기"];
// 배열을 돌며 윈하는 것을 할 때
fruits.forEach(function (value, index, array) {
console.log("--------------------"); // --------------------
console.log(value); // 바나나 // 딸기 // 포도 // 딸기
console.log(index); // 0 // 1 // 2 // 3
console.log(array); // [ '바나나', '딸기', '포도', '딸기' ]
});
// value만 사용하는 경우
fruits.forEach((value) => console.log(value)); // 바나나
// 딸기
// 포도
// 딸기
const item1 = { name: "우유", price: 1 };
const item2 = { name: "쿠키", price: 3 };
const item3 = { name: "빵", price: 2 };
const products = [item1, item2, item3, item2];
// 제일 먼저 조건 (콜백함수) 에 맞는 아이템 반환
let result = products.find((value) => value.name === "쿠키");
console.log(result); // { name: '쿠키', price: 3 }
// 제일 먼저 조건 (콜백함수) 에 맞는 아이템의 인덱스 반환
result = products.findIndex((value) => value.name === "쿠키");
console.log(result); // 1
// 배열의 아이템들이 부분적으로 조건 (콜백함수) 에 맞는지 boolean 값 반환
result = products.some((item) => item.name === "쿠키");
console.log(result); // true
// 배열의 아이템들이 전부 조건 (콜백함수) 에 맞는지 boolean 값 반환
result = products.every((item) => item.name === "쿠키");
console.log(result); // false
// 조건에 맞는 모든 아이템들을 새로운 배열로 반환 (새로운)
result = products.filter((item) => item.name === "쿠키");
console.log(result); // [ { name: '쿠키', price: 3 }, { name: '쿠키', price: 3 } ]
const nums = [1, 2, 3, 4, 5];
// 배열의 아이템들을 각각 다른 아이템으로 변환해서 새로운 배열 생성하여 반환 (새로운)
result = nums.map((item) => item * 2);
console.log(result); // [ 2, 4, 6, 8, 10 ]
result = nums.map((item) => {
if (item % 2 === 0) return item * 2;
else return item;
});
console.log(result); // [ 1, 4, 3, 8, 5 ]
// 중첩된 배열을 펴서 하나의 배열로 반환 (새로운)
result = nums.map((item) => [1, 2]);
console.log(result); // [ [ 1, 2 ], [ 1, 2 ], [ 1, 2 ], [ 1, 2 ], [ 1, 2 ] ]
result = nums.flatMap((item) => [1, 2]);
console.log(result); // [
// 1, 2, 1, 2, 1,
// 2, 1, 2, 1, 2
// ]
result = ["mal", "lang"].flatMap((text) => text.split(""));
console.log(result); // [
// 'm', 'a', 'l', 'l',
// 'a', 'n', 'g'
// ]
const numbers = [0, 5, 4, 2, 1, 10];
// 문자열 형태의 오름차순으로 요소를 정렬하여 반환, 기존의 배열을 변경 (업데이트)
const texts = ["hi", "abc"];
texts.sort();
console.log(texts); // [ 'abc', 'hi' ]
numbers.sort();
// 문자열 형태로 정렬됨
console.log(numbers); // [ 0, 1, 10, 2, 4, 5 ]
// _ < 0 : a가 앞으로 정렬, 오름차순
// _ > 0 : b가 앞으로 정렬, 내림차순
numbers.sort((a, b) => a - b);
console.log(numbers); // [ 0, 1, 2, 4, 5, 10 ]
// 배열의 요소들을 접어서 값을 하나로
// 0 : initialValue -> sum 의 초기값을 0으로
result = [1, 2, 3, 4, 5].reduce((sum, value) => (sum += value), 0);
console.log(result); // 15
'💠프로그래밍 언어 > JavaScript' 카테고리의 다른 글
[마스터 개념] 5 | map, 유용한 연산자들 (1) | 2022.11.01 |
---|---|
[마스터 개념] 4 | 이터러블 (0) | 2022.11.01 |
[마스터 개념] 2 | 객체, 클래스, 빌트인 객체 (0) | 2022.10.26 |
[마스터 개념] 1 | 변수, 연산자, 함수 (1) | 2022.10.25 |
[정리] 3 | DOM 트리, 접근하기 & 새로운 요소 추가, 노드 삭제 정리 (0) | 2022.08.29 |