카테고리 없음

JavaScript 자주 사용하는 활용법 정리

0to1ton 2023. 8. 24. 08:38

이번 글에서는 JavaScript로 로직, 아이디어를 구현할 때 자유자재로 코딩을 하기 위해 자주 쓰는 구문들을 정리해보려고 한다. 

  1. 형 변환
    1. number -> string 변환하는 3가지 방법
      1. String(50) -> "50"
      2. 50.toString() -> "50"
      3. 50 + "" -> "50"
    2. string -> number 변환하는 4가지 방법
      1. Number("50") -> 50
      2. parseInt("50") -> 50
      3. parseInt("12.4") -> 12
      4. +"5" -> 5
      5. -"5"  -> 5
  2. string(문자열) ->  array(배열)로 변환하는 방법
    예제 str = "abcd"
    1. str.split("") -> ['a', 'b', 'c', 'd']
      1. 'orange🍊'.split(''); // [ 'o', 'r', 'a', 'n', 'g', 'e', '\ud83c', '\udf4a' ]
      2. '1,2,3,4'.split(',') // ['1', '2', '3', '4']
      3. '1,2,3,4'.split(',').map(Number)  // [1,2,3,4]
    2. spread [...str]
      1. [...'orange🍊']; // ['o',  'r', 'a', 'n',  'g', 'e', '🍊']
    3. Array.from(str)
      1. Array.from('orange🍊'); // ['o',  'r', 'a', 'n',  'g', 'e', '🍊']
  3. array(배열) -> string(문자열)로 변환하는 방법
    예제: arr = ['a', 'b', 'c', 'd']
    1. arr.toString() // 'a,b,c,d,e'
    2. console.log(arr.toString()); // a,b,c,d,e
    3. console.log(arr.join()); // a,b,c,d,e
    4. console.log(arr.join('')); // abcde
    5. console.log(arr.join('+'));  // a+b+c+d+e
  4. 새로운 값 추가하기
    1.  배열
        1. unshift()
        1. push
      1. 중간
        1. splice (start-inclusive, deleteCount-inclusive, addItem)
          1. nums = [0,1,2,3];
          2. console.log(nums.splice(1,2,5)); // [1,2]
          3. console.log(nums); // [0,5,3]
  5. 값 빼는 방법
    1. 배열 
        1. shift()
        1. pop()
      1. 중간
        1. splice(start-inclusive, deleteCount-inclusive)
        2. slice(start-inclusive, end-exclusive)
  6. 정렬하기 (Sort)
    1. 문자정렬
      1.  
      2. 오름차순
        1. let words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
          console.log(words.sort()); // 오름차순: ['A', 'Z', 'a',    'c', 'd', 'f',    'g', 'z'  ]
        2. 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'  ]
        3. words3 = ["a", "c", "z", "e"];
          console.log("word3: ", words3.sort((a, b) => a - b)); // 오름차순: word3:  [ 'a', 'c', 'z', 'e' ]
        4. 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'  ]
        5. 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']
        6. 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']
      3. 내림차순
        1. words = ["a", "c", "d", "z", "g", "f", "A", "Z"];
          console.log(words.reverse()); // 내림차순: ['Z', 'A', 'f',    'g', 'z', 'd',    'c', 'a'  ]
        2. 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'  ]
        3. 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']
        4. 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']
    2. 숫자 정렬
      1. 문제점
        1. 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;
      2. 오름차순
        1. numbers = [1, 22, 5, 3333, 11, 444];
          console.log(numbers.sort((a, b) => a - b)); // [ 1, 5, 11, 22, 444, 3333 ]
      3. 내림차순
        1. numbers = [1, 22, 5, 3333, 11, 444];
          console.log(numbers.sort(function (a, b) { return b - a })); // [ 3333, 444, 22, 11, 5, 1 ]
    3. 객체 정렬
      1. let objects = [
            { name: 'banana', price: 3000 },
            { name: 'apple', price: 39900 },
            { name: 'coconut', price: 2000 }
        ];
      2. 오름차순
        1. console.log(objects.sort((a, b) => {
              if (a.name < b.name) {
                  return -1;
              } else if (a.name > b.name) {
                  return 1;
              } else {
                  return 0;
              }
          }));
        2. [
            { name: 'apple', price: 39900 },
            { name: 'banana', price: 3000 },
            { name: 'coconut', price: 2000 }
          ]
      3. 내림차순
        1. console.log(objects.sort((a, b) => {
              return a.name < b.name - 1 ? 1 : a.name > b.name ? -1 : 0;
          }));
        2. [
            { name: 'coconut', price: 2000 },
            { name: 'banana', price: 3000 },
            { name: 'apple', price: 39900 }
          ]
  7. 조건문
    1. 배열 안에 있는지 확인 (includes)
      1. let arr = [1, 2 , 3, 1, 4, 1]; 
        1. console.log(arr.includes(1)); // true
    2. 문자열 안에 있는지 확인 (includes)
      1. let arr_s = "abcde";
        console.log(arr_s.includes("a")); // true
        console.log(arr_s.includes("ab")); // true
    3. 배열안에 있는지 filter
      1. let arr = [1, 2 , 3, 1, 4, 1]; 
        1. console.log(arr.filter(v => v === 1)); // [1,1,1]
        2. console.log(arr.filter(v => v === 1) === [1, 1, 1]); // false
  8. 문자열 교체하기 String.replace()
    1. let arr_s = "abcde";
    2. console.log(arr_s.replace("a", "z")); // zbcde
  9. 문자열 문자 어디에 있나 찾기: string.indexOf('c');
    1. arr_s = "abcde";
    2. console.log(arr_s.indexOf('c')); // 2
  10. 배열 반대로 뒤집기 Array.reverse();
    1. nums = [0,1,2,3];
    2. console.log(nums.reverse()); // [ 3, 2, 1, 0 ]
  11. 배열 합산하기 - reduce
    1. Array.reduce((acc, cur, idx) => acc + cur), 0)
  12. 반복문  (배열 숫자 합산하기)
    1. for loop
      1. arr = [1,2,3,4,5]
      2.     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
    2. for of
      1. arr = [1,2,3,4,5]
      2.     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
    3. for in
      1. arr = [1,2,3,4,5]
      2.     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
    4. for each
      1. arr = [1,2,3,4,5]
      2.     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
    5. map
      1. arr = [1,2,3,4,5]
      2.     let sum_map = 0;
            arr.map(i => sum_map += i)
            console.log("--sum_map: " + sum_map); // --sum_map: 15
    6. reduce
      1. arr = [1,2,3,4,5]
      2.     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
  13. 제곱근, 루트
    1. Math.sqrt()
    2. Math.pow()
  14. Array인지 확인하기
    1. nums= [1,2,3]
    2. console.log(Array.isArray(nums)); // true
  15. Array 복사하기
  16. 진법 전환
    1. 10진법에서 X진법 전환
      1. console.log((100).toString(3)); // 10201  10진법 100을 -> 3진법 10201로 전환
      2. console.log((289).toString(4)); // 10201  10-> 4
    2. 3진법에서 10진법으로 전환: parseInt((100), 3))
      1. console.log(parseInt((100), 3)); // 9 
        // 1*3^2 + 0*3^1 + 0*3^0 = 9
      2. console.log(parseInt((10201), 3)); // 100
        // 10201 = 1*3^4 + 0*3^3 + 2*3^2 + 0*3^1 + 1*1^0 = 100
      3. console.log(parseInt((10201), 4)); // 289
        // 10201 = 1*4^4 + 0*4^3 + 2*4^2 + 0*4^1 + 1*4^0 = 289
  17. 아스키
    1. // 알파벳 총 수는 26개 (abcdefghijklmnopqrstuvwxyz)
      // ascii -> A 65, Z 90, a 97 z 122
      // 아스키 숫자 뽑을 때 : 문자열.charCodeAt(i) 
      // 아스키 문자 뽑을 때 : String.fromCharCode(97)
    2. let s_sample = "abc"; // 97 98 99 
      1. console.log(s_sample.charCodeAt(0)); // 97
      2. console.log(String.fromCharCode(97)); // a