1. Math
1.1 Math.floor (내림,바닥)
- MDN Math.floor
- 바닥, 내림 함수
- 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환
1console.log(Math.floor(5.95)) // 52console.log(Math.floor(5.05)) // 53console.log(Math.floor(5)) // 54console.log(Math.floor(-5.05)) // -6
1.2 Math.ceil (올림, 천장)
- MDN Math.ceil
- 주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자를 integer 로 반환
1Math.ceil(0.95) // 12Math.ceil(4) // 43Math.ceil(7.004) // 84Math.ceil(-0.95) // -05Math.ceil(-4) // -46Math.ceil(-7.004) // -7
1.3 Math.sqrt() : 제곱근
1.4 Math.abs() : 절대값
2. Number
2.1 문자열 파싱, parseInt()
- MDN parseInt()
- cf.
parse: (문장을 문법적으로) 분석하다 - cf.
int: integer의 약어, 숫자
2.1.1 파라미터
1parseInt(string, radix)
- string : 숫자로 변환할 문자열
- radix
- optional
- string 문자열을 읽을 진법(수의 진법 체계의 진법)
- 2~36의 수
2.1.2 리턴
string을 정수로 변환한 값을 리턴합니다.
만약, string의 첫 글자를 정수로 변경할 수 없으면 NaN(Not a Number) 값을 리턴합니다.
2.1.3 10진법 처리
1// 1. 문자열을 정수로 리턴, 음수 표현 가능2console.log(parseInt('10')) // 103console.log(parseInt('-10')) // -1045// 2. 소수점은 제거 후, 정수값만 리턴6console.log(parseInt('10.9')) // 1078// 3. 문자열이 아닌 다른 타입이 전다뢰면, 문자열로 변환해 리턴9console.log(parseInt(10)) // 101011// 4. 숫자가 아닌 문자 이후의 값은 무시, 그 이전 숫자만 변환12console.log(parseInt('10n')) // 1013console.log(parseInt('10nnn13')) // 101415// 5. 처음에 오는 공백 문자는 허용, 뒤에 공백은 무시16console.log(parseInt(' 10')) // 1017console.log(parseInt('10 ')) // 101819// 6. 첫 글자가 숫자가 아니면 NaN(Not a Number)을 리턴20console.log(parseInt('k10')) // NaN21console.log(parseInt('')) // NaN
2.1.4 2진법, 16진법 처리
1// 1. 10진법 -> 2진법2console.log(parseInt('10', 2)) // 234// 2. 2진법에는 2라는 숫자가 없어서, NaN5console.log(parseInt('2', 2)) // NaN67// cf. 16진법을 컴퓨터에서 표현하려면, 'Ox' 또는 'OX'로 시작8// 3. 16진법 -> 10진법9console.log(parseInt('0xF')) // 1510console.log(parseInt('0XF')) // 151112// 4. 16진수 범위 0~F, 16진수 범위 밖의 문자는 무시13console.log(parseInt('0XFkk')) // 15
3. String.prototype
3.1 replaceAll (대체하다), replace
1str.replace(regexp|substr, newSubstr|function)2// 첫번째 파라미터 : 정규표현식(RegExp) | 문자열 String,3// 두번쨰 파라미터 : 첫번째 파라미터를 대신할 문자열 String | 대신해서 호출할 함수45replaceAll(pattern, replacement)6// 첫번째 파라미터 : 문자열, 또는 symbol.replace메서드가 있는 객체, e.g. 정규표현식7// 두번째 파라미터 : 문자열, 함수
- MDN replaceAll
- MDN replace
- 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환
1const p = 'lazy dog. If the dog reacted, was it really lazy?'23// 📝 1. replace() : 첫 번쨰 해당하는 문자열만 치환4console.log(p.replace('dog', 'monkey'))5// lazy monkey. If the dog reacted, was it really lazy?"67const regex = /Dog/i // 정규표현식도 사용 가능8console.log(p.replace(regex, 'ferret'))9// lazy ferret. If the dog reacted, was it really lazy?"1011// 📝 2. replaceAll() : 해당하는 모든 문자열 치환12console.log(p.replaceAll('dog', 'monkey'))13// lazy monkey. If the monkey reacted, was it really lazy?"1415const regex = /Dog/gi16console.log(p.replaceAll(regex, 'ferret'))17// lazy ferret. If the ferret reacted, was it really lazy?"1819// **** 응용 예시20const text = '안녕하세요'21console.log(text.replace('안녕', '안녕#')) // 안녕#하세요22console.log(text.replace('안녕', '안녕#').split('#')) // [ '안녕', '하세요' ]2324const text2 = '철수안녕하세요'25console.log(text2.replace('안녕', '#안녕#').split('#')) // [ '철수', '안녕', '하세요' ]2627// **** 시크릿 코드를 만들어 겹치지 않게 하는 법28const text3 = '철수안녕하세요'29console.log(text3.replace('안녕', '#@$%안녕#@$%').split('#@$%')) // [ '철수', '안녕', '하세요' ]
3.2 substr() ☢️
- MDN String.prototype.substr()
- 문자열에서 특정 위치에서 시작하여 특정 문자 수 만큼의 문자들을 반환
- 다만, String.prototype.substr()은 바람직한 특징때문에 사용처가 없으면 명세에서 제거될 수 있다고 합니다.
3.3 localeCompare()
- MDN String.prototype.localeCompare()
- 참조 문자열이 정렬 순으로 지정된 문자열 앞 혹은 뒤에 오는지 또는 동일한 문자열인지 나타내는 수치를 반환
3.4 repeat()
- MDN String.prototype.repeat()
- 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환
3.5 substring()
- MDN String.prototype.substring()
- string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환
substring(시작 인덱스, 끝 인덱스-미포함)
1const str = 'Mozilla'23console.log(str.substring(1, 3)) // "oz"4console.log(str.substring(2)) // "zilla"
3.6 padStart()
- MDN String.prototype.padStart()
- 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환
- 채워넣기는 대상 문자열의 시작(좌측)부터 적용
padStart(목표문자열길이, 채워넣을 다른 문자열)
1'abc'.padStart(10) // " abc"2'abc'.padStart(10, 'foo') // "foofoofabc"3'abc'.padStart(6, '123465') // "123abc"4'abc'.padStart(8, '0') // "00000abc"5'abc'.padStart(1) // "abc"
4. Array.prototype
- 여러 개체(Entity) 값을 순차적으로 나열한 선형 자료구조
- 대표 속성(perperty)과 메서드(method)
배열 크기 및 배열 여부 확인: Array.length, Array.isArray()배열 추가/삭제: Array,push(), Array.pop(), Array.shift(), Array.unshift(), Array.splice(), Array.slice() 등배열 탐색: Array.index.Of(), Array.lastindexOf(), Array.includes()배열 변형: Array.sort(), Array.reverse(), Array.join()배열 반복: Array.sort(), Array.forEach(), Array.map(), Array.find(), Array.filter(), Array.reduce()배열 논리연산: Array.some(), Array.every()
선언:new Array()혹은[]를 통해 선언하며, 사이즈 혹은 값을 입력하여 초기화도 가능접근 방법:Array[index]를 통해, index를 통하여 O(1)에 접근배열 속성:Array.length를 통해, 배열 요소의 개수 확인 가능
4.1 JS 배열의 실체
자바스크립트에서 배열은 다른 언어에서 말하는 일반적인 배열이 아닌Hash 기반의 객체- 메모리가 연속적인 밀집 배열(dense array)가 아닌 비 연속적인 희소 배열(sparse array)
1let nums = []23nums.push('one')4nums.push('two')5console.log(nums.length) // 26console.log(nums) // [ 'one', 'two' ]78nums['once'] = 'once'9nums['twice'] = 'twice'10console.log(nums.length) // 211console.log(nums) // [ 'one', 'two', once: 'once', twice: 'twice' ]1213console.log(Object.getOwnPropertyDescriptor(nums))
4.2 Array.isArray() : 존재 여부
1let num = 123.4562let str = 'Here I am!'3let fruits = ['apple', 'orange', 'melon']45// Array.isArray : 배열이면 true, 아니면 false6console.log(Array.isArray(num)) // false7console.log(Array.isArray(str)) // false8console.log(Array.isArray(fruits)) // true
4.3 delete array[index] : 일부 요소 삭제
1let fruits = ['🍎', '🍑', '🍌']23console.log(fruits) // [ '🍎', '🍑', '🍌' ]4console.log(fruits.length) // 356// 배열 일부 요소 삭제, 삭제해도 배열 사이즈가 그대로인 문제점이 존재7delete fruits[1]8console.log(fruits) // [ '🍎', <1 empty item>, '🍌' ]9console.log(fruits.length) // 3
4.4 unshift, shift : 앞에서 추가, 삭제
1let fruits = ['🍎', '🍑', '🍌']23// (1) Array.shift() : 배열 앞에서 삭제4ret = fruits.shift()5console.log(fruits) // [ '🍑', '🍌' ]6console.log(ret) // 🍎78// (2) Array.unshift(element) : 배열 앞에서 추가9ret = fruits.unshift('🍉')10console.log(fruits) // [ '🍉', '🍑', '🍌' ]11console.log(ret) // 3
4.5 push, pop : 뒤에서 추가, 삭제
1let fruits = ['🍎', '🍑', '🍌']23// Array.push(element) : 배열 뒤에서 추가4ret = fruits.push('🍉')5console.log(fruits) // [ '🍎', '🍑', '🍌', '🍉' ]6console.log(ret) // 478// Array.pop() : 배열 뒤에서 삭제9ret = fruits.pop()10console.log(fruits) // [ '🍎', '🍑', '🍌' ]11console.log(ret) // 🍉
4.6 splice(연결, 붙이다) : 배열 삭제 및 변경
- MDN Array.prototype.splice()
- 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경
splice(시작인덱스, 제거할 요소의 수, 배열에 추가할 요소)- deleteCount : 0 이하라면 어떤 요소도 제거X (optional)
- item1, item2, … : 배열에 추가할 요소를 생략하면 제거만 수행 (optional)
1const months = ['Jan', 'March', 'April', 'June']23months.splice(1, 0, 'Feb') // 1번 인덱스에 삽입4console.log(months) // [ 'Jan', 'Feb', 'March', 'April', 'June' ]56months.splice(4, 1, 'May') // 4번 인덱스에 1개 요소 대체7console.log(months) // [ 'Jan', 'Feb', 'March', 'April', 'May' ]
4.7 slice(잘라내기) : 배열 자르고 새 배열 생성
- MDN Array.prototype.slice()
- 어떤 배열의
begin 인덱스부터end 인덱스까지- (
end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다.
- (
- 원본 배열은 바뀌지 않습니다.
1// slice(시작인덱스, end인덱스-미포함)2const fruits = ['🍎', '🍓', '🍌', '🍊', '🍇']34// 2번 인덱스부터5console.log(fruits.slice(2)) // [ '🍌', '🍊', '🍇' ]67// 2번 인덱스부터 4번 인덱스 이전까지8console.log(fruits.slice(2, 4)) // [ '🍌', '🍊' ]910// 1번 인덱스부터 5번 인덱스 이전까지11console.log(fruits.slice(1, 5)) // [ '🍓', '🍌', '🍊', '🍇' ]1213// 뒤에서 2 인덱스까지14console.log(fruits.slice(-2)) // [ '🍊', '🍇' ]1516// 2번 인덱스부터 뒤에서 1 인덱스까지17console.log(fruits.slice(2, -1)) // [ '🍌', '🍊' ]1819// 원본 배열은 변경되지 않음20console.log(fruits.slice()) // [ '🍎', '🍓', '🍌', '🍊', '🍇' ]
4.8 concat : 배열 병합
1let fruits = ['🍎', '🍑', '🍌']23console.log(fruits.concat('🍓')) // [ '🍎', '🍑', '🍌', '🍓' ]4console.log(fruits.concat(['🍒', '🥭'])) // [ '🍎', '🍑', '🍌', '🍒', '🥭' ]5console.log(fruits.concat(['🍒', '🥭'], '🍇')) // [ '🍎', '🍑', '🍌', '🍒', '🥭', '🍇' ]
4.9 배열 반복문⭐
- 다양한 반복문 문법을 통해 배열 요소에 접근 가능
- 반복문 문법
for...length(index 접근)for...of (element 접근): 배열 순회용- 반복 가능한 객체(iterable)를 순회
- 즉,
[Symbol.iterator]속성을 가지는 것들만 사용가능
for...in (key 접근): 객체 순회용- cf. 사실 JS에서는 배열도 객체라
for...in을 사용해서 index를 가져올 수 있다. - 즉, key를 리턴 (배열의 경우에는 index)
- cf. 사실 JS에서는 배열도 객체라
Array.prototype.forEach (element, index, 호출한array 접근)
1let fruits = ['사과', '오렌지', '바나나']23// 💡 1. use for (index)4for (let i = 0; i < fruits.length; i++) {5console.log(i) // 0 1 26console.log(fruits[i]) // 사과 오렌지 바나나7}89// 💡 2. use for...(element) of10for (let fruit of fruits) {11console.log(fruit) // 사과 오렌지 바나나12}1314// 💡 3. use for...(key) in15for (let key in fruits) {16console.log(key) // 0 1 217console.log(fruits[key]) // 사과 오렌지 바나나18}
4.10 forEach()⭐
배열 요소 별 콜백 함수 각각에 실행 : Array.forEach(function(item, index, array){})
item: 배열 요소index: 배열 위치array: 배열
4.10.1 element와 index 출력
1const numbers = [15, 23, 17, 65, 78]23numbers.forEach((element, index) => {4console.log(`Value : ${element}, Index : ${index}`)5})67// Value : 15, Index : 08// Value : 23, Index : 19// Value : 17, Index : 210// Value : 65, Index : 311// Value : 78, Index : 4
4.10.2 호출한 콜백함수 출력
1const numbers = [15, 23, 17, 65, 78]23numbers.forEach((element, index, array) => {4console.log(array)5})67// [ 15, 23, 17, 65, 78 ]8// [ 15, 23, 17, 65, 78 ]9// [ 15, 23, 17, 65, 78 ]10// [ 15, 23, 17, 65, 78 ]11// [ 15, 23, 17, 65, 78 ]
4.10.3 단점
await을 루프 내부에 쓸 수 없음forEach()중간에 루프를 탈출하는 것이 곤란. 다른 문법의 경우엔,break로 가능
4.10.4 다른 반복문과 forEach
for-of로 다른 순회문에서 할 수 있는 모든 것을 할 수 있어서 가장 좋다.- 성능에 대한 비교는 사실 의미가 X
- (엄밀히 따지면
forEach가 제일 느리다.) - 그러나 JS에서 성능이 유의미할 정도로 순회문을 돌아야 하면, 웹 어셈블리 등 다른 방법을 알아보는 것이 좋다.
- (엄밀히 따지면
- 프론트엔드 개발에서
for-of를 돌아야 하는 일은 거의 없고,- 대부분이
mapreduce를 사용해서 해결할 수 있고, 그 쪽이 더 함수형이고 읽기도 간결하다.
- 대부분이
4.11 map (사상,대응)
- MDN Array.prototype.map()
- map(맵)의 사전적 의미
- 지구 표면의 전부나 일부를 일정한 비율로 줄여 약속된 기호를 사용하여 평면에 그린 그림
- 어떤 사실이나 주어진 자료 등을 분석하여 그 관계를 알기 쉽게 나타낸 표.
- 『물리』 물체에서 나온 빛이 거울에 반사 또는 굴절된 다음에 모여서 생기는 상
- 『수학』 어떤 집합의 임의의 원소가 다른 집합의 하나의 원소에 대응할 때, 그 두 집합 간의 대응 관계
- mapping는 ’지도를 만든다‘는 뜻이지만, 메모리 맵(memory map)을 제작하는 것을 말함.
- 컴퓨터를 사용해 지도 데이터를 작성하는 일을 말하거나
- 롤플레잉 게임 등의 배경이 되는 미로나 지도를 플레이어가 작성하는 것도
- 사상(mapping, 베낄 사, 모양 상)이라고 함
배열.map((요소, 인덱스, 호출한배열), this로 사용되는 값)
1const array1 = [1, 4, 9, 16]2const map1 = array1.map(x => x * 2)34console.log(map1) // Array [2, 8, 18, 32]
4.12 sort (정렬)
- MDN Array.prototype.sort()
- 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다.
- 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.
- 문자열 배열인 경우 알파벳순으로 정렬 (첫글자 기준, A~Z)
- 숫자를 문자열로 정렬하면 “2”가 “1”보다 크므로 “25”가 “100”보다 큼⭐
- 때문에 숫자를 정렬할 때 잘못된 결과를 생성
- 비교 기능을 제공하여 이 문제를 해결 가능
4.12.1 오른차순 정렬
1array.sort(function (a, b) {2return a - b3}) // 오름차순4array.sort((a, b) => a - b)
- 함수는 두 값을 비교할 때
sort()값을 비교 함수로 보내고 반환된(음수, 0, 양수) 값에 따라 값을 정렬합니다.- 음수면, b 앞에 정렬된다.
- 양수면, a 앞에 정렬된다.
- 결과가 0이면 두 값의 정렬 순서가 변경되지 않습니다.
4.12.2 내림차순 정렬
- 40과 100을 비교할 떄, (40, 100)
(a - b)일 떄 (40 - 100)을 계산하면 결과가 음수(-60)이므로- sort()는 40을 100보다 작은 값으로 정렬
1array.sort((a, b) => b - a) // 내림차순
4.13 indexOf, lastIndexOf : 인덱스 탐색
-
index 탐색 (앞에서부터) :
Array.indexOf(item, from)- MDN Array.prototype.indexOf()
- 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환
-
index 탐색(뒤에서부터) :
Array.lastIndexOf(item, from)
1let fruits = ['apple', 'orange', 'banana', 'orange', 'melon']23// arr.indexOf(searchElement[, fromIndex])4// arr.indexOf(배열에서 찾을 요소, 검색을 시작할 색인-option)5console.log(fruits.indexOf('orange')) // 16console.log(fruits.indexOf('Orange')) // -17console.log(fruits.indexOf('orange', 2)) // 389console.log(fruits.lastIndexOf('orange')) // 310console.log(fruits.lastIndexOf('orange', -3)) // 111console.log(fruits.lastIndexOf('orange', 0)) // -11213console.log(fruits.includes('banana')) // true14console.log(fruits.includes('Banana')) // false15console.log(fruits.includes(0)) // false
4.14 indexOf : 인덱스 포함여부
- MDN Array.prototype.indexOf()
- 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환
1// arr.indexOf(searchElement[, fromIndex])2// arr.indexOf(배열에서 찾을 요소, 검색을 시작할 색인-option)3const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']45console.log(beasts.indexOf('bison')) // 16console.log(beasts.indexOf('bison', 2)) // 47console.log(beasts.indexOf('giraffe')) // -1
4.15 reverse : 배열 반전
1let nums = [1, -1, 4, 5, 2, 0]23console.log(nums.sort()) // [ -1, 0, 1, 2, 4, 5 ]4console.log(nums.reverse()) // [ 5, 4, 2, 1, 0, -1 ]56let fruits = ['apple', 'orange', 'banana', 'melon']7console.log(fruits.sort()) // [ 'apple', 'banana', 'melon', 'orange' ]8console.log(fruits.reverse()) // [ 'orange', 'melon', 'banana', 'apple' ]
4.16 filter (거르다)
- MDN filter
- 주어진 배열을 순회하면서 콜백 함수의 반환값이 true에 해당하는 요소로만 구성된 새로운 배열을 생성하여 반환.
- 한마디로 find()의 찾아서 값을 반환하는 기능과 map()의 배열 생성 기능의 융합 버젼.
1const numberArr = [1, 2, 3, 4, 5]23const numberFilterArr = numberArr.filter(item => {4return item % 2 === 0 // 해당조건에 부합으면 item을 넣어 배열 반환5})67console.log(numberFilterArr) // [2, 4]
4.16.1 파라미터
콜백 함수의 조건을 만족하는 값을 배열로 반환 : Array.filter(function(item, index, array) {}
item: 배열 요소index: 배열 위치array: 배열
1let users = [2{ name: 'bob', age: 17, job: false },3{ name: 'alice', age: 20, job: false },4{ name: 'john', age: 27, job: true },5]67// filter : 조건을 만족하는 값을 배열로 반환8let filter_job = users.filter(function (user) {9return user.job == false10})11console.log(filter_job)12// [13// { name: "bob", age: 17, job: false },14// { name: "alice", age: 20, job: false },15// ]1617let filter_age = users.filter(function (user) {18return user.age > 1919})20console.log(filter_age)21// [22// { name: "alice", age: 20, job: false },23// { name: "john", age: 27, job: true },24// ]
4.17 reduce (줄이다)
- MDN reduce
- 배열을 순회하면서, callback 함수를 실행하고, 하나의 리턴 값을 반환하는 함수
- 누적 계산의 결과 값 반환
- 누산기 (acc), 현재 값 (cur), 현재 인덱스 (idx), 원본 배열 (src) 4개의 매개변수를 가짐
- 누산기(accumulator) = 계산 결과를 저장해놓는 곳 = 연산 장치에 일시적으로 저장하는 레지스터 = 묶을 누, 셈 산, 그릇 기
1const arr = [1, 2, 3, 4, 5]2const result = arr.reduce((acc, cur) => {3return (acc += cur)4}, 0)5console.log(result) // 1567const arr2 = [1, 2, 3, 4, 5]8const result2 = arr2.reduce((acc, cur) => {9return (acc += cur)10}, 10)11console.log(result2) // 25
4.17.1 파라미터
- 요소 별 함수 수행 누적 결과값 반환 :
Array.reduce(function(accumulator, item, index, array){})accumulator: 이전 함수 결과(initial로 초기값 설정 가능)item: 배열 요소index: 배열 위치array: 배열
1let nums = [1, 2, 3, 4, 5]2let call_count = 034console.log('result\tvalue\tindex')5let sum = nums.reduce(function (accumulator, item, index, array) {6console.log(accumulator, '\t\t', item, '\t\t', index)7call_count++8return accumulator + item9}, 0) // initial 없다면 index 1부터 시작10/* 결과11result value index120 1 0131 2 1143 3 2156 4 31610 5 417*/1819console.log(call_count) // 520console.log(sum) // 15
4.18 split (나눈다)
- MDN String.prototype.split
- e.g. 리그오브레전드(롤)에서 ‘스플릿 푸쉬’(분열되서 나눠서 라인을 민다)
- String 객체를 구분자를 이용하여 여러 개의 문자열로 나눔
1const str = 'The quick brown fox jumps over the lazy dog.'23const words = str.split(' ')4console.log(words[3]) // "fox"56const chars = str.split('')7console.log(chars[8]) // "k"89const strCopy = str.split()10console.log(strCopy) // Array ["The quick brown fox jumps over the lazy dog."]1112// **** 응용 예시13const text = '안녕하세요'14console.log(text.replace('안녕', '안녕#')) // 안녕#하세요15console.log(text.replace('안녕', '안녕#').split('#')) // [ '안녕', '하세요' ]1617const text2 = '철수안녕하세요'18console.log(text2.replace('안녕', '#안녕#').split('#')) // [ '철수', '안녕', '하세요' ]1920// **** 시크릿 코드를 만들어 겹치지 않게 하는 법21const text3 = '철수안녕하세요'22console.log(text3.replace('안녕', '#@$%안녕#@$%').split('#@$%')) // [ '철수', '안녕', '하세요' ]
4.19 join (합친다) : 배열 값을 문자열로 변환
- MDN Array.prototype.join()
- 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.
1const elements = ['Fire', 'Air', 'Water']23console.log(elements.join()) // "Fire,Air,Water"4console.log(elements.join('')) // "FireAirWater"5console.log(elements.join('-')) // "Fire-Air-Water"
4.19.1 split-reverse-join : 문자열 뒤집기
1문자열.split('').reverse().join('')23// 1. 문자사이에 공백을 기준으로 배열로4// 2. 뒤집고5// 3. 문자사이에 공백을 기준으로 문자열로
4.20 fill()
- MDN Array.prototype.fill()
- 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채움
4.21 Array.from
- MDN Array.from()
- 문자열 등 유사 배열(Array-like) 객체나 이터러블한 객체를 배열로 만들어주는 메서드
유사 배열 객체란, 키가 인덱스 값으로 되어있고 길이를 나타내는 length 속성을 갖는 객체를 의미
1// 1. 문자열을 배열로 만드는 예시2console.log(Array.from('Hello'))3// [ 'H', 'e', 'l', 'l', 'o' ]45// 2. 유사 배열 객체를 배열로 만드는 예시6console.log(Array.from({ 0: '찬민', 1: '희진', 2: '태인', length: 3 }))7// [ '찬민', '희진', '태인' ]89// 3. 함수의 매개변수들을 순서대로 배열로 만드는 예시10const funcA = (...arguments) => {11return Array.from(arguments)12}13console.log(funcA(1, 2, 3, 4, 5))14// [ 1, 2, 3, 4, 5 ]
Array.from() 의 첫 번째 인자는 배열로 만들 이터러블한 객체가 되며, 두 번째 인자는 생성한 배열의 모든 원소에 대해 수행할 맵핑 함수입니다. (Array.map() 이라고 생각하시면 됩니다.)
한번 Array.from()과 반복문을 활용해 1부터 31까지의 수를 원소로 갖는 배열을 생성해 보겠습니다.
1// 맵핑 함수의 첫 번째 인자 언더스코어(_) 는 특별한 인자가 아니라,2// 불필요한 인자의 공간을 채우기 위한 용도입니다.3const arr = Array.from(Array(31), (_, index) => index + 1)45console.log(arr)
4.22 find()
- 콜백 함수의 조건을 만족하는, 단 하나의 값만 반환 :
Array.find(function(item, index. array) {})item: 배열 요소index: 배열 위치array: 배열
1let users = [2{ name: 'bob', age: 17, job: false },3{ name: 'alice', age: 20, job: false },4{ name: 'john', age: 27, job: true },5]67// find : 조건에 맞는 하나의 값만 반환8let find_job = users.find(function (user) {9return user.job == false10})11console.log(find_job) // { name: 'bob', age: 17, job: false }1213let find_age = users.find(function (user) {14return user.age > 1915})16console.log(find_age) // { name: 'alice', age: 20, job: false }
4.23 some()
- 배열 내 단 하나라도 콜백 함수의 조건을 만족하는 요소가 있다면 true, 아니면 false반환 (빈 배열일 경우 false)
Array.some(function(item, index, array) {})item: 배열 요소index: 배열 위치array: 배열
1let users = [2{ name: 'bob', age: 17, job: false },3{ name: 'alice', age: 20, job: false },4{ name: 'john', age: 27, job: true },5]67// some : 조건을 만족하는 요소가 있다면 true8let some_job = users.some(function (users) {9return users.job == false10})11console.log(some_job) // true1213let some_age = users.some(function (users) {14return users.age < 1615})16console.log(some_age) // false1718let empty = [].some(item => item > 16)19console.log(empty) // false
4.24 every()
- 배열 내 모든 요소가 콜백 함수의 조건을 만족하는 요소가 있다면 true, 아니면 false반환 (빈 배열일 경우 false)
Array.every(function(item, index, array) {})item: 배열 요소index: 배열 위치array: 배열
1let users = [2{ name: 'bob', age: 17, job: false },3{ name: 'alice', age: 20, job: false },4{ name: 'john', age: 27, job: true },5]67let some_job = users.every(function (users) {8return users.job == false9})10console.log(some_job) // false1112let some_age = users.every(function (users) {13return users.age > 1614})15console.log(some_age) // true1617let empty = [].every(item => item > 16)18console.log(empty) // true
4.25 N차원 배열
- 배열 안에 N개 만큼의 배열이 존재하는 객체
- 2/3차원 지도 정보, RGB를 저장하는 2차원 사진 파일 등을 표현할 떄 활용 가능
1let array = [2[101, 102, 103],3[201, 202, 203],4[301, 302, 303],5]67console.log(array)8console.log(array[0]) // [ 101, 102, 103 ]9console.log(array[1][0]) // 20110console.log(array[2][2]) // 3031112let arr_2 = array.pop()13console.log(array.length) // 214console.log(arr_2) // [ 301, 302, 303 ]15console.log(array) // [ [ 101, 102, 103 ], [ 201, 202, 203 ] ]1617let array_num = array.push([401, 402, 403])18console.log(array.length) // 319console.log(array_num) // 320console.log(array) // [ [ 101, 102, 103 ], [ 201, 202, 203 ], [ 401, 402, 403 ] ]2122for (let i = 0; i < array.length; i++) {23for (let j = 0; j < array[i].length; j++) {24array[i][j] += 100025console.log(array[i][j]) // 1101 ... 140326}27}
5. Map 객체
Map객체는 key,value에 해당하는 자료구조
5.1 set => 값 추가
1// 형태2맵 객체.set(key,value)34// 예시5var map = new Map()67map.set(1, 'value1')8map.set(2, 'value2')910console.log(map)11// => Map(2) { 1 => 'value1', 2 => 'value2' }
5.2 get => value 획득
1// 형태2맵 객체.get(key)34// 예시5var map = new Map()67map.set(1, 'value1')8map.set(2, 'value2')910console.log(map.get(2))11// => value2
5.3 has => 값 있는지 체크
1// 형태2맵 객체.has(key)34// 예시5var map = new Map()67map.set(1, 'value1')8map.set(2, 'value2')910console.log(map.has(2)) // => true11console.log(map.has(3)) // => false
5.4 delete => 값 지우기
1// 형태2맵 객체.delete(key);34// 예시5var map = new Map()67map.set(1, 'value1')8map.set(2, 'value2')910map.delete(2)1112console.log(map.has(2)) // => false
원하는 key에 대한 값을 지운다.
5.5 size => Map의 요소 개수
1// 형태2맵 객체.size34// 예시5var map = new Map()67map.set(1, 'value1')8map.set(2, 'value2')910console.log(map.size) // => 2
map의 개수를 구한다. 단, 함수형태로 호출해선 안된다. 주의해야한다.
5.6 Map 객체 순환하기
1// 형태2for(let [key,value] of 맵 객체) { ... }34// 예시5var map = new Map()67map.set(1, { id: 'aaa', password: 1111 })8map.set(2, { id: 'bbb', password: 2222 })9map.set(3, { id: 'ccc', password: 3333 })1011for (let [key, value] of map) {12console.log(value.id)13}14// => aaa15// => bbb16// => ccc
5.7 Map 정렬하기
1// 형태 => 배열로 만들어서 정렬하고 다시 Map객체로 바꿈2var arr = [...맵 객체];3arr.sort(...);4var newMap = new Map(arr)56//예시7var map = new Map()89map.set(1, { id: 'aaa', password: 2222 })10map.set(2, { id: 'bbb', password: 3333 })11map.set(3, { id: 'ccc', password: 1111 })1213var arr = [...map]14arr.sort((a, b) => {15if (a[1].password < b[1].password) {16return 117} else return -118})1920var newMap = new Map(arr)2122console.log(newMap)23// 출력24// Map(3) {25// 2 => { id: 'bbb', password: 3333 },26// 1 => { id: 'aaa', password: 2222 },27// 3 => { id: 'ccc', password: 1111 },28// }
6. Set
중복을 허용하지 않는 value를 가진 자료구조
6.1 add => 값 추가
1// 형태2셋 객체.add(value)34// 예시5var set = new Set()67set.add('value1')8set.add('value2')910console.log(set) // => Set(2) { 'value1', 'value2' }
Set객체.add(value) 형태로 넣어주면 된다.
6.2 has => 값 있는지 체크
1// 형태2셋 객체.has(value)34// 예시5var set = new Set()67set.add('value1')8set.add('value2')910console.log(set.has('value1')) // => true11console.log(set.has('value3')) // => false
인자로 받은 value가 있는지 체크 true/false 리턴
6.3 delete => 값 지우기
1// 형태2셋 객체.delete(values);34// 예시5var set = new Set()67set.add('value1')8set.add('value2')910set.delete('value2')1112console.log(set.has('value2')) // => false
원하는 value에 대한 값을 지운다.
6.4 size => Map의 요소 개수
1// 형태2셋 객체.size;34// 예시5var set = new Set()67set.add('value1')8set.add('value2')910console.log(set.size) // => 2
set의 요소 개수를 구한다. 단, 맵과 마찬가지로 함수형태로 호출해선 안된다. 주의해야한다.
6.5 Set 객체 순환하기
1// 형태2for(let value of 셋 객체) { ... }34// 예시5var set = new Set()67set.add({ id: 'aaa', password: 1111 })8set.add({ id: 'bbb', password: 2222 })9set.add({ id: 'ccc', password: 3333 })1011for (let value of set) {12console.log(value.id)13}14// => aaa15// => bbb16// => ccc
6.6 Set 정렬하기
맵과 마찬가지로 배열로 갔다가 정렬하고 다시 Set으로 오는 과정을 취한다.
1// 형태 => 배열로 만들어서 정렬하고 다시 Set객체로 바꿈2var arr = [...셋 객체]3arr.sort(...)4var newSet = new Set(arr)56// 예시7var set = new Set()89set.add({ id: 'aaa', password: 2222 })10set.add({ id: 'bbb', password: 1111 })11set.add({ id: 'ccc', password: 3333 })1213var sortArr = [...set]14sortArr.sort((a, b) => {15if (a.password > b.password) return 116else return -117})1819var newSet = new Set(sortArr)20console.log(newSet)2122// 출력23// Set(3) {24// { id: 'bbb', password: 1111 },25// { id: 'aaa', password: 2222 },26// { id: 'ccc', password: 3333 },27// }