기본정리 - Javascript(9)

given·2024년 11월 4일

FE-기본

목록 보기
14/14
post-thumbnail

Javascript 기본

표준 내장 객체

자바스크립트 엔진에 기본적으로 내장되어있는 객체.

⚠️ 파괴적 메서드, 비파괴적 메서드 : 원본 데이터에 영향을 주는지 아닌지

1.Object

2.Function

3.Array

4.String

5.Boolean

6.Number

7.Math

8.Date

9.RegEXP

1. 문자열 표준 내장 객체

  1. lengh

    문자열 길이 반환

  2. charAt(index)

    인덱스 문자를 가져올 때

  3. indexOf(string)

    시작 인덱스 찾기 (사용성 높음)

  4. lastIndexOf(string)

    마지막 인덱스 찾기(끝에서)

    const str = "Hello, world! Hello";
    console.log(str.indexOf("Hello")); // 0
    console.log(str.lastIndexOf("Hello")); // 14
  5. subStrdeprecated / substring()

    substring(start, end) → start부터 end 인덱스까지 자름: 비파괴적

    const str = "Hello, world! Hello";
    console.log(str.substring(0, 4)); //Hell
    conosle.log(str); //"Hello, world! Hello"
  6. slice(index)

    index 번호까지 문자열 자름 (사용성 높음)

    const str = "Hello, world! Hello";
    console.log(str.slice(4)); //o, world! Hello
    console.log(str.slice(-1)); //o <- index가 음수면 뒤에서 자름
    console.log(str.slice(-3)); //llo <- index가 음수면 뒤에서 자름
  7. toLowerCase()

    모두 소문자로 바꿈 (사용성 높음)

  8. toUpperCase()

    모두 대문자로 바꿈 (사용성 높음)

  9. trim()

    문자열 양쪽 공백을 제거 (사용성 매우 높음)

  10. split()

    문자열을 주어진 구분자로 분할하여 배열로 반환

  11. replace(string, change)

    주어진 문자열을 교체할 때 사용 - 첫 등장 시

  12. replaceAll(string, change)

    주어진 문자열을 교체할 때 사용 - 모두 변경

  13. includes(문자열)

    true, false (사용성 매우 높음)

  14. startWith(문자열)

    문자열로 시작하면 true, false (사용성 높음)

  15. endsWith(문자열)

    문자열로 끝나면 true, false

  16. repeat(conut)

    count 만큼 반복(알고리즘)

  17. padStrart(length, str)

    문자열의 길이가 주어진 길이보다 짧을 경우

  18. padEnd()

  19. valueOf()

  20. match()

  21. search()

  22. localeCompare()

    두 문자열을 비교하여 정렬 순서를 반환, -1, 1, 0

2. 배열 내장 객체

  1. push()

    배열 요소중 뒤에 추가

  2. pop()

    배열 요소 중 가장 뒤 제거 후 그 요소 반환

  3. shift()

    배열 중 첫번째 제거 후 그 요소 반환 ← pop의 반대

  4. unshift()

    배열의 시작에 하나 이상의 요소를 추가 ← push의 반대

  5. slice()

    배열의 일부를 얕은 복사본으로 반환 ← 비파괴적

  6. splice()

    배열의 기존 요소를 제거하거나 대체하거나 새 요소를 추가

    const fruits = ['사과', '바나나', '오렌지'];
    fruits.splice(1, 1, '포도'); // 인덱스 1에서 1개 요소를 '포도'로 대체
    console.log(fruits); // ['사과', '포도', '오렌지']
  7. forEach()

    배열의 각 요소에 대해 순회하며 제공된 함수를 실행

  8. map()

    배열의 각 요소에 대해 주어진 함수를 호출한 결과로 새로운 배열을 생성

  9. filter()

    주어진 함수를 통과하는 모든 요소로 구성된 새로운 배열을 생성 ← 조건문이 true여야함

  10. find()

    주어진 함수를 만족하는 첫 번째 요소를 반환. 없으면 undefined

  11. some()

    배열의 일부 요소가 조건을 만족하는지, 만족하는 요소가 있으면 true, 없으면 false

    const arr = [1, 2, 3, 4, 5];
    const isFour = arr.some((value) => value >= 4);
    console.log(isFour); // true
  12. every()

    모든 배열의 요소가 조건에 만족하면 true, 하나라도 안되면 false

  13. includes()

    배열이 특정 요소를 포함하는지 확인

  14. join()
    배열의 모든 요소를 문자열로 결합

    ```jsx
    const arr = [1, 2, 3, 4, 5];
    const join = arr.join("@");
    console.log(join); //1@2@3@4@5
    ```
  15. reverse()

    배열의 요소 순서를 반전 ← 파괴적(원본배열 변경됨)

  16. sort()

    배열의 요소를 정렬 ← 파괴적(원본배열 변경됨)

    // 얕은 복사
    const arr = [2, 1, 3, 4, 5];
    const arr2 = arr;
    arr2.sort();
    console.log(arr); // [ 1, 2, 3, 4, 5 ]
    console.log(arr2); // [ 1, 2, 3, 4, 5 ]
    
    //깊은 복사
    const arr = [2, 1, 3, 4, 5];
    const arr2 = [...arr];
    arr2.sort();
    console.log(arr);// [ 2, 1, 3, 4, 5 ]
    console.log(arr2);// [ 1, 2, 3, 4, 5 ]

    sort()는 string 타입을 내리기 때문에 내부 함수에서 조작이 필요하다.

    const arr = [6, 2, 1, 3, 4, 5, 15];
    
    arr.sort();
    console.log(arr); // [1, 15, 2, 3, 4,  5, 6]

    반환되는 값이 음수면 a가 b보다 앞으로 오고

    양수면 b를 a보다 앞으로 한다. 0을 반환하면 순서를 바꾸지 않는다.

    const arr = [6, 2, 1, 3, 4, 5, 15];
    
    arr.sort((a, b) => {
      if (a < b) return -1; // 음수
      else if (a > b) return 1; // 양수
      else return 0; // 0
    });
    console.log(arr);
    const arr = [6, 2, 1, 3, 4, 5, 15]; 
    
    arr.sort((a, b) => a - b); 
    console.log(arr); //[ 1, 2,  3, 4, 5, 6, 15 ] 오름 차순
    arr.sort((a, b) => b - a);
    console.log(arr); //[ 15, 6, 5, 4, 3, 2, 1 ] 내림 차순

    string 고차함수와 같이 쓸수 있음

    const items = [
      { name: "Sharpe", age: 18 },
      { name: "James", age: 16 },
      { name: "Charie", age: 20 },
    ];
    const items2 = [
      { name: "Sharpe", age: 18 },
      { name: "James", age: 16 },
      { name: "Charie", age: 20 },
    ];
    
    items.sort((a, b) => {
      const A = a.name.toUpperCase();
      const B = b.name.toUpperCase();
      if (A < B) return -1;
      else if (A > B) return 1;
      else return 0;
    });
    console.log(items); // <--- 1.
    
    items2.sort((a, b) =>
      a.name.toUpperCase().localeCompare(b.name.toLocaleLowerCase())
    );
    console.log(items2); // <---- 2. 둘이 동일함 
  17. findIndex()

    주어진 조건을 만족하는 요소의 인덱스를 반환

    const numbers = [10, 20, 30, 40];
    const index = numbers.findIndex(num => num > 25);
    console.log(index); // 2
  18. indexOf()

    배열에서 특정 요소의 첫 번째 인덱스를 반환 ↔ lastIndexOf()도 있다.

    const fruits = ['사과', '바나나', '오렌지'];
    const index = fruits.indexOf('바나나');
    console.log(index); // 1
  19. flat()

    다차원 배열을 평면 배열로 변환. 기본적으로 1단계 깊이의 배열을 평평하게 만들고, 깊이를 지정.

    const nestedArr = [1, [2, 3], [4, [5, 6]]];
    const flatArray = nestedArr.flat();
    
    console.log(flatArray); // [ 1, 2, 3, 4, [ 5, 6 ] ]
    const nestedArr = [1, [2, 3], [4, [5, 6]]];
    const flatArray = nestedArr.flat(2); //
    
    console.log(flatArray); // [ 1, 2, 3, 4, 5, 6 ]
  20. fill()

    배열의 모든 요소를 정해진 값으로 채움. 시작 인덱스와 종료 인덱스를 지정.

    const arr = new Array(5).fill(0);
    console.log(arr); // [0, 0, 0, 0, 0]
  1. reduce() ← ⭐️ 제일 중요
    배열의 각 요소에 대해 함수를 실행하여 단일 값을 반환
    
    ```jsx
    const arr = [1, 2, 3, 4, 5];
    
    const sum = arr.reduce((prev, current, index) => {
      console.table({ prev, current, index });
      return prev + current;
    }, 0);
    
    const sum = arr.reduce((a,b)=>a+b);
    ```
    
    초기값을 배열을 사용
    ```js
    const arr = [1, 2, 3, 3, 4, 5];

const uniqueArr = arr.reduce((a, b) => {
if (!a.includes(b)) a.push(b);
return a;
}, []);
console.log(uniqueArr);

## 1. Math 객체

1. `abs()`
2. `ceil()`
3. `floor()`
4. `round()`
    
    ```jsx
    console.log(Math.abs(-5)); // 절대값
    console.log(Math.ceil(4.5)); // 올림 -> 주어진 수보다 크거나 같은 정수 중에서 가장 작은 값을 반환
    console.log(Math.floor(4.5)); // 내림 -> 주어진 수보다 크거나 같은 정수 중에서 가장 큰 값을 반환
    console.log(Math.round(4.3)); // 반올림 -> .5 이상
    ```
    
5. `random()` 
    
    0 이상 1 미만의 난수를 생성
    
    ```jsx
    console.log(Math.random()); 
    ```
    
    보통 단독으로 쓰지 않음
    
    ```jsx
    // 1부터 45까지의 랜덤한 숫자가 필요할 때
    console.log(Math.random() * 45); //0~45 사이 소수점 숫자가 나옴
    console.log(Math.floor(Math.random() * 45) + 1); // 정수가 필요할 때
    ```
    
6. `min()`
7. `max()`
8. `sqrt()`
    
    ```jsx
    // 삼각형, 사인, 코사인, 탄젠트
    // Math.sin(), Math.cos(), Math.tan()
    
    // 피타고랏스 정의 수식 => a2 + b2 = c2
    function caclulateYpotenuse(a, b) {
      return Math.sqrt(Math.pow(a, 2) + Map.pow(b, 2));
    }
    ```
    

## 2. Date 객체

날짜 정보

```jsx
const date = new Date();
console.log(date); // 브라우저: Mon Nov 04 2024 12:14:55 GMT+0900 (한국 표준시) /2024-11-04T03:18:29.942Z
console.log(date.getFullYear()); // 연도
console.log(date.getMonth() + 1); // 월(index) 1월 -> 0, 2월 -> 1 ...
console.log(date.getDate()); // 일 1 - 31

날짜 포맷팅

const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const dates = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
const dates2 = String(date.getDate()).padStart(2, "0");

console.log(`${year}-${month}-${dates}`); // YYYY-MM-DD

시간 정보

console.log(date.getHours()); // 시
console.log(date.getMinutes()); // 분
console.log(date.getSeconds()); // 초

요일정보

console.log(date.getDay()) // 0 - 6 -> 0(일) ~ 6(토)
const daysString = ["일", "월", "화", "수", "목", "금", "토", "일"];
console.log(daysString[date.getDay()]);

다른 날짜의 인스턴스 객체 생성법

const date = new Date("2024-11-20");
console.log(date); // Wed Nov 20 2024 09:00:00 GMT+0900 (한국 표준시)
console.log(date.getFullYear()); // 2024
console.log(date.getMonth() + 1); // 11
console.log(date.getDate()); // 20

객체 이후 변경(set)

const date = new Date();
date.setFullYear(2025); 
date.setMonth(0);
date.setDate(1);

간단한 포맷팅 toLocaleDateString()

자바스크립트가 실행되는 지역(local)에 맞는 포맷팅 ISO 639-1 한국(”ko-KR”)

en-CAYYYY-MM-DD ← 완벽하진 않음

console.log(date.toLocaleDateString()); // 2024. 11. 4.

날짜 차이

const date1 = new Date();
const date2 = new Date("2024-12-04");

console.log(date1);
console.log(date2 - date1); // 밀리 세컨드 2573777203 ms
const date1 = new Date();
const date2 = new Date("2024-12-04");
const dateDiff = Math.abs(date2 - date1); // 절댓값 <- 음수가 안나오게
const diffDay = dateDiff / (60 * 60 * 24 * 1000); //초 * 분 * 시 * 밀리세컨
console.log(Math.ceil(dateDiff));

⚠️ 프론트의 날짜 시간대와 서버의 날짜 시간대
프론트는 한국 표준시 서버는 UTC ↔
서버측에서 Timezone, Asia / Seoul

profile
osanThor⚡️블로그 이전했습니다. https://blog.given-log.com

0개의 댓글