카테고리 없음
JavaScript 자주 사용하는 활용법 정리
0to1ton
2023. 8. 23. 21:54
이번 글에서는 JavaScript로 로직, 아이디어를 구현할 때 자유자재로 코딩을 하기 위해 자주 쓰는 구문들을 정리해보려고 한다.
- 형 변환
- number -> string 변환하는 3가지 방법
- String(50) -> "50"
- 50.toString() -> "50"
- 50 + "" -> "50"
- string -> number 변환하는 4가지 방법
- Number("50") -> 50
- parseInt("50") -> 50
- parseInt("12.4") -> 12
- +"5" -> 5
- -"5" -> 5
- number -> string 변환하는 3가지 방법
- string(문자열) -> array(배열)로 변환하는 방법
예제 str = "abcd"- str.split("") -> ['a', 'b', 'c', 'd']
- 'orange🍊'.split(''); // [ 'o', 'r', 'a', 'n', 'g', 'e', '\ud83c', '\udf4a' ]
- '1,2,3,4'.split(',') // ['1', '2', '3', '4']
- '1,2,3,4'.split(',').map(Number) // [1,2,3,4]
- spread [...str]
- [...'orange🍊']; // ['o', 'r', 'a', 'n', 'g', 'e', '🍊']
- Array.from(str)
- Array.from('orange🍊'); // ['o', 'r', 'a', 'n', 'g', 'e', '🍊']
- str.split("") -> ['a', 'b', 'c', 'd']
- array(배열) -> string(문자열)로 변환하는 방법
예제: arr = ['a', 'b', 'c', 'd']
- arr.toString() // 'a,b,c,d,e'
- console.log(arr.toString()); // a,b,c,d,e
- console.log(arr.join()); // a,b,c,d,e
- console.log(arr.join('')); // abcde
- console.log(arr.join('+')); // a+b+c+d+e
- 새로운 값 추가하기
- 배열
- 앞
- unshift()
- 뒤
- push
- 중간
- splice (start-inclusive, deleteCount-inclusive, addItem)
- nums = [0,1,2,3];
- console.log(nums.splice(1,2,5)); // [1,2]
- console.log(nums); // [0,5,3]
- splice (start-inclusive, deleteCount-inclusive, addItem)
- 앞
- 배열
- 값 빼는 방법
- 배열
- 앞
- shift()
- 뒤
- pop()
- 중간
- splice(start-inclusive, deleteCount-inclusive)
- slice(start-inclusive, end-exclusive)
- 앞
- 배열
- 정렬하기 (Sort)
- 문자정렬
- 오름차순
- let words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.sort()); // 오름차순: ['A', 'Z', 'a', 'c', 'd', 'f', 'g', 'z' ] - words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.sort((a, b) => a - b)); // 오름차순: ['a', 'c', 'd', 'z', 'g', 'f', 'A', 'Z' ] - words3 = ["a", "c", "z", "e"];
console.log("word3: ", words3.sort((a, b) => a - b)); // 오름차순: word3: [ 'a', 'c', 'z', 'e' ] - words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.sort((a, b) => a > b ? 1 : -1)); // 오름차순: ['A', 'Z', 'a', 'c', 'd', 'f', 'g', 'z' ] - words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.sort((a, b) => a - b)); // ['a', 'c', 'd', 'z', 'g', 'f', 'A', 'Z'] - words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.sort((a, b) => a.localeCompare(b))); // ['a', 'A', 'c', 'd', 'f', 'g', 'z', 'Z']
- let words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
- 내림차순
- words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.reverse()); // 내림차순: ['Z', 'A', 'f', 'g', 'z', 'd', 'c', 'a' ] - words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.sort((a, b) => a < b ? 1 : -1)); // 내림차순: ['z', 'g', 'f', 'd', 'c', 'a', 'Z', 'A' ] - words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.sort((a, b) => b - a)); // 내림차순: ['a', 'c', 'd', 'z', 'g', 'f', 'A', 'Z'] - words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
console.log(words.sort((a, b) => b.localeCompare(a))); // ['Z', 'z', 'g', 'f', 'd', 'c', 'A', 'a']
- words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
- 숫자 정렬
- 문제점
- let numbers = [1, 22, 5, 3333, 11, 444];
// 문제상황 발생: 기본 sort()는 문자열 정렬이기에 문자열로 정렬해버림. 1 다음에 5가 나와야하는데 11이 나옴
console.log(numbers.sort()); // [ 1, 11, 22, 3333, 444, 5 ];
console.log(numbers.sort(), typeof (numbers.sort()[0])); // [ 1, 11, 22, 3333, 444, 5 ], number;
- let numbers = [1, 22, 5, 3333, 11, 444];
- 오름차순
- numbers = [1, 22, 5, 3333, 11, 444];
console.log(numbers.sort((a, b) => a - b)); // [ 1, 5, 11, 22, 444, 3333 ]
- numbers = [1, 22, 5, 3333, 11, 444];
- 내림차순
- numbers = [1, 22, 5, 3333, 11, 444];
console.log(numbers.sort(function (a, b) { return b - a })); // [ 3333, 444, 22, 11, 5, 1 ]
- numbers = [1, 22, 5, 3333, 11, 444];
- 문제점
- 객체 정렬
- let objects = [
{ name: 'banana', price: 3000 },
{ name: 'apple', price: 39900 },
{ name: 'coconut', price: 2000 }
]; - 오름차순
- console.log(objects.sort((a, b) => {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
})); - [
{ name: 'apple', price: 39900 },
{ name: 'banana', price: 3000 },
{ name: 'coconut', price: 2000 }
]
- console.log(objects.sort((a, b) => {
- 내림차순
- console.log(objects.sort((a, b) => {
return a.name < b.name - 1 ? 1 : a.name > b.name ? -1 : 0;
})); - [
{ name: 'coconut', price: 2000 },
{ name: 'banana', price: 3000 },
{ name: 'apple', price: 39900 }
]
- console.log(objects.sort((a, b) => {
- let objects = [
- 문자정렬
- 조건문
- 배열 안에 있는지 확인 (includes)
- let arr = [1, 2 , 3, 1, 4, 1];
- console.log(arr.includes(1)); // true
- let arr = [1, 2 , 3, 1, 4, 1];
- 문자열 안에 있는지 확인 (includes)
- let arr_s = "abcde";
console.log(arr_s.includes("a")); // true
console.log(arr_s.includes("ab")); // true
- let arr_s = "abcde";
- 배열안에 있는지 filter
- let arr = [1, 2 , 3, 1, 4, 1];
- console.log(arr.filter(v => v === 1)); // [1,1,1]
- console.log(arr.filter(v => v === 1) === [1, 1, 1]); // false
- let arr = [1, 2 , 3, 1, 4, 1];
- 배열 안에 있는지 확인 (includes)
- 문자열 교체하기 String.replace()
- let arr_s = "abcde";
- console.log(arr_s.replace("a", "z")); // zbcde
- 문자열 문자 어디에 있나 찾기: string.indexOf('c');
- arr_s = "abcde";
- console.log(arr_s.indexOf('c')); // 2
- 배열 반대로 뒤집기 Array.reverse();
- nums = [0,1,2,3];
- console.log(nums.reverse()); // [ 3, 2, 1, 0 ]
- 배열 합산하기 - reduce
- Array.reduce((acc, cur, idx) => acc + cur), 0)
- 반복문 (배열 숫자 합산하기)
- for loop
- arr = [1,2,3,4,5]
- let sum_for = 0;
for (let i = 0; i < arr.length; i++) {
sum_for += arr[i]
}
console.log("--sum_for: " + sum_for); // --sum_for: 15
- for of
- arr = [1,2,3,4,5]
- let sum_forof = 0;
for (let i of arr) {
console.log(i, typeof(i)); // 1,2,3,4,5 number
sum_forof += i;
//console.log(sum_forof+=i);
}
console.log("--sum_forof: " + sum_forof); // --sum_forof: 15
- for in
- arr = [1,2,3,4,5]
- let sum_forin = 0;
for (let i in arr) {
// console.log(i, typeof(i)); // 0,1,2,3,4 string
sum_forin += arr[i];
//console.log(sum_forof+=i);
}
console.log("--sum_forin: " + sum_forin); // --sum_forin: 15
- for each
- arr = [1,2,3,4,5]
- let sum_foreach = 0;
arr.forEach(i => sum_foreach += i); // 1 + 2 + 3 + 4 -> 10
console.log("--sum_foreach: " + sum_foreach);
// sum_foreach += item
// sum_foreach = sum_foreach+ item
// 0 = 0 + 1 = 1
// 1 = 1 + 2 = 3 = foreach
// 3 = 3 + 3 = 6 = foreach
// 6 = 6 + 4 = 10 = foreach
// console.log(sum_foreach); // --sum_foreach: 15
- map
- arr = [1,2,3,4,5]
- let sum_map = 0;
arr.map(i => sum_map += i)
console.log("--sum_map: " + sum_map); // --sum_map: 15
- reduce
- arr = [1,2,3,4,5]
- const sum_reduce = arr.reduce((acc, num) => acc + num, 0);
// 1,2,3,4 -> 1 -> 3 -> 6 -> 10
const sum_reduce_func = arr.reduce(function (acc, num) {
return acc + num
}, 0); // 1,2,3,4 -> 1 -> 3 -> 6 -> 10
console.log("--sum_reduce: " + sum_reduce); --sum_reduce: 15
console.log("--sum_reduce_func: " + sum_reduce_func); // --sum_reduce_func: 15
- for loop
- 제곱근, 루트
- Math.sqrt()
- Math.pow()
- Array인지 확인하기
- nums= [1,2,3]
- console.log(Array.isArray(nums)); // true
- Array 복사하기
- 진법 전환
- 10진법에서 X진법 전환
- console.log((100).toString(3)); // 10201 10진법 100을 -> 3진법 10201로 전환
- console.log((289).toString(4)); // 10201 10-> 4
- 3진법에서 10진법으로 전환: parseInt((100), 3))
- console.log(parseInt((100), 3)); // 9
// 1*3^2 + 0*3^1 + 0*3^0 = 9 - console.log(parseInt((10201), 3)); // 100
// 10201 = 1*3^4 + 0*3^3 + 2*3^2 + 0*3^1 + 1*1^0 = 100 - console.log(parseInt((10201), 4)); // 289
// 10201 = 1*4^4 + 0*4^3 + 2*4^2 + 0*4^1 + 1*4^0 = 289
- console.log(parseInt((100), 3)); // 9
- 10진법에서 X진법 전환
- 아스키
- // 알파벳 총 수는 26개 (abcdefghijklmnopqrstuvwxyz)
// ascii -> A 65, Z 90, a 97 z 122
// 아스키 숫자 뽑을 때 : 문자열.charCodeAt(i)
// 아스키 문자 뽑을 때 : String.fromCharCode(97) - let s_sample = "abc"; // 97 98 99
- console.log(s_sample.charCodeAt(0)); // 97
- console.log(String.fromCharCode(97)); // a
- // 알파벳 총 수는 26개 (abcdefghijklmnopqrstuvwxyz)