ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JavaScript에서 반드시 마스터해야 할 19가지 필수 팁과 트릭
    Javascript 2023. 11. 19. 18:10

    JavaScript를 마스터하면 개발 효율성과 코드 품질을 크게 향상시킬 수 있습니다. 이 글에서는 반드시 마스터해야 할 JavaScript 기술 19가지를 소개합니다. 이 팁들은 더 깔끔하고 효율적인 코드를 작성하는 데 도움이 되며, 개발 과정에서 많은 시간을 절약할 수 있습니다.

     

    1. 배열에서 최대값과 최소값 계산하기

    배열에서 최대값 또는 최소값을 찾는 것은 Math.maxMath.min을 사용하거나, reduce를 사용하여 더 동적인 방식으로 할 수 있습니다.

    const arrayNumbers = [-1, 10, 6, 5, -3];
    const getMax = (array) => array.reduce((max, num) => (max > num ? max : num));
    const getMin = (array) => array.reduce((min, num) => (min < num ? min : num));
    
    const max = getMax(arrayNumbers); // 10
    const min = getMin(arrayNumbers); // -3
    console.log(`최대값=${max}`); // 최대값=10
    console.log(`최소값=${min}`); // 최소값=-3

     

    2. 배열 합계 및 누적 계산하기

    reduce를 사용하면 여러 숫자를 쉽게 더하거나 누적할 수 있습니다.

    // 배열 합계
    const sum = (...nums) => nums.reduce((sum, num) => sum + num);
    
    // 누적 계산
    const accumulator = (...nums) => nums.reduce((acc, num) => acc * num);
    
    const arrayNumbers = [1, 3, 5];
    console.log(accumulator(1, 2, 3)); // 6
    console.log(accumulator(...arrayNumbers)); // 15
    console.log(sum(1, 2, 3, 4, 5)); // 15
    console.log(sum(...arrayNumbers)); // 9

     

    3. 검색 파라미터 형식화하기

    URL 유형의 검색 파라미터를 얻는 것은 자주 다루어야 하는 기능입니다.

    // URL: https://www.example.com/index.html?name=devpoint&id=100
    // 검색 파라미터 형식화
    const parseQuery = (search = window.location.search) =>
      search
        .replace(/(^\?)|(&$)/g, "")
        .split("&")
        .reduce((query, it) => {
          const [key, value] = it.split("=");
          query[key] = decodeURIComponent(value);
          return query;
        }, {});
    
    console.log(parseQuery("?name=devpoint&id=100")); // { name: 'devpoint', id: '100' }

     

    4. 검색 파라미터 직렬화하기

    링크로 이동할 때 검색 파라미터를 추가하는 것은 수동으로 연결하는 것보다 편리합니다.

    const searchObj = {
      name: "devpoint",
      id: 100,
    };
    
    const stringifySearch = (search = {}) =>
      Object.entries(search)
        .reduce(
          (t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,
          Object.keys(search).length ? "?" : ""
        )
        .replace(/&$/, "");
    
    const strLink = `https://www.example.com/index.html${stringifySearch(searchObj)}`;
    console.log(strLink); // https://www.example.com/index.html?name=devpoint&id=100

     

    5. 다단계 중첩 배열 평탄화하기

    다단계 중첩 배열을 평탄화하는 방법은 무엇일까요?

    const array = [1, [2, [3, [4, [5]]]]];
    
    const flat = (arrayNumbers) =>
      arrayNumbers.reduce(
        (acc, it) => acc.concat(Array.isArray(it) ? flat(it) : it),
        []
      );
    const flatArray = flat(array);
    console.log(flatArray); // [ 1, 2, 3, 4, 5 ]

     

    6. 배열 구성원 수 세기

    각 구성원의 수를 세는 방법은 다음과 같습니다.

    const count = (array) =>
      array.reduce(
        (acc, it) => (acc.set(it, (acc.get(it) || 0) + 1), acc),
        new Map()
      );
    const array = [1, 2, 1, 2, -1, 0, "0", 10, "10"];
    console.log(count(array));

     

    7. 객체의 여러 속성 얻기

    API를 통해 백엔드 데이터를 얻은 후 프론트엔드는 대개 일부 데이터만 필요로 합니다.

    const getObjectKeys = (obj = {}, keys = []) =>
      Object.keys(obj).reduce(
        (acc, key) => (keys.includes(key) && (acc[key] = obj[key]), acc),
        {}
      );
    
    const obj = {
      a: 1,
      b: 2,
      c: 3,
      d: 4,
      e: 5,
    };
    const newObj = getObjectKeys(obj, ["a", "b", "c", "d"]);
    console.log(newObj); // { a: 1, b: 2, c: 3, d: 4 }

     

    8. 배열 문자열 찾기

    includes를 사용하면 코드를 간결하게 작성할 수 있습니다.

    const myTech = 'JavaScript';
    const techs = ['HTML', 'CSS', 'JavaScript'];
    
    // Common writing method
    if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') {
        // do something
    }
    
    // includes writing method
    if (techs.includes(myTech)) {
        // do something 
    }

     

    9. 배열 중복 제거하기

    reduce를 사용하면 배열 중복 제거도 쉽게 할 수 있습니다.

    const array = [1, 2, 1, 2, -1, 10, 11];
    const uniqueArray = array.reduce(
      (acc, it) => (acc.includes(it) ? acc : [...acc, it]),
      []
    );
    
    console.log(uniqueArray); // [ 1, 2, -1, 10, 11 ]

     

    10. 메소드 flat 시뮬레이션하기

    JavaScript에는 이미 중첩된 배열을 평탄화하는 기능을 구현한 기본 메소드가 있지만, 이 기능을 어떻게 완전히 구현할 수 있을까요? 다음은 reduce를 사용하여 그 기능을 구현하는 방법입니다.

    Array.prototype.flat2 = function (n = 1) {
      const len = this.length;
      let count = 0;
      let current = this;
      if (!len || n === 0) {
        return current;
      }
      const hasArray = () => current.some((it) => Array.isArray(it));
      while (count++ < n && hasArray()) {
        current = current.reduce((result, it) => result.concat(it), []);
      }
      return current;
    };
    
    const array = [1, [2, [3, [4, [5]]]]];
    console.log(array.flat2(Infinity)); // [ 1, 2, 3, 4, 5 ]

     

    이러한 JavaScript 팁과 트릭을 마스터함으로써 개발 과정에서 더 빠르고 효율적으로 작업할 수 있으며, 코드의 품질도 향상될 것입니다.

     

    그외에도 다양한 효율적인 코딩 스타일이 있습니다.

     

    11. 배열에서 거짓 값 제거

    filter() 메서드와 Boolean을 결합하여 배열에서 거짓 값(예: null, undefined, 빈 문자열, 0, NaN, false)을 쉽게 제거할 수 있습니다.

    let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];
    let filterArray = arr.filter(Boolean); // [12, 'xyz', -25, 0.5]

     

    12. Null 병합 연산자 (??)

    변수가 null 또는 undefined일 때 기본값을 제공하려면 null 병합 연산자를 사용하세요.

    const username = data ?? 'medium';

     

    13. 논리적 OR 할당 연산자 (`||=`)

    변수에 기본값을 할당할 때 논리적 OR 할당 연산자를 사용할 수 있습니다.

    let count;
    count ||= 0;

     

    14. 다중 값 매칭

    다중 값을 매칭할 때는 배열을 사용하고 includes() 메서드로 검사합니다.

    if (['admin', 'user', 'guest'].includes(role)) {
        // 특정 역할에 해당하는 경우의 로직
    }

     

    15. 화살표 함수

    클래식 함수는 화살표 함수로 간소화할 수 있습니다. 화살표 함수는 짧고, this가 렉시컬하게 바인딩되므로 더욱 편리합니다.

    const greet = name => console.log(`Hello, ${name}`);

     

    16. 매개변수 분해

    객체 리터럴 또는 배열에서 필요한 데이터만 추출할 때 매개변수 분해를 사용할 수 있습니다.

    const { name, age } = person;

     

    17. 스프레드 연산자 (...)

    스프레드 연산자는 배열 또는 객체를 합치거나 복사하는 데 유용합니다.

    const combinedArray = [...arr1, ...arr2];
    const copiedObject = {...originalObject};

     

    18. 과학적 표기법

    큰 숫자를 간단하게 표현하기 위해 과학적 표기법을 사용할 수 있습니다.

    for (let i = 0; i < 1e6; i++) {
        // 반복 로직
    }

     

    19. for...of, in 루프

    루프는 배열이나 이터러블 객체를 간결하게 순회할 수 있게 해줍니다.

    for (let str of arr) {
      console.log("item: ", str);
    }
    
    arr.forEach((str) => {
      console.log("item: ", str);
    });
    
    for (let index in arr) {
      console.log(index, arr[index]);
    }
Designed by Tistory.