자바스크립트 내장 함수 및 메소드

jjyu_my·2024년 10월 6일
0

JAVASCRIPT

목록 보기
5/15
post-thumbnail

📌 기본 내장 객체

🔎 Object 객체

  • Object() : 객체를 생성합니다
const obj = new Object();
obj.name = "John";
console.log(obj); // { name: "John" }
  • hasOwnProperty(prop): 객체가 특정 속성을 가지고 있는지 확인합니다
const person = { name: "Alice" };
console.log(person.hasOwnProperty("name")); // true
  • keys(): 객체의 모든 키를 배열로 반환합니다
const person = { name: "Alice", age: 25 };
console.log(Object.keys(person)); // ["name", "age"]
  • values(): 객체의 모든 값을 배열로 반환합니다
const person = { name: "Alice", age: 25 };
console.log(Object.values(person)); // ["Alice", 25]

🔎 Function 객체

  • Function(): 새로운 함수를 생성합니다
const greet = new Function("name", "return `Hello, ${name}!`;");
console.log(greet("Alice")); // "Hello, Alice!"
  • call(): 다른 객체의 메소드로 함수를 호출합니다
function greet() {
  return `Hello, ${this.name}!`;
}
const person = { name: "Alice" };
console.log(greet.call(person)); // "Hello, Alice!"
  • apply(): 인수를 배열 형태로 제공하여 함수를 호출합니다
function sum(a, b) {
  return a + b;
}
console.log(sum.apply(null, [5, 10])); // 15

📌 데이터 구조

🔎 Array 객체

  • Array(): 배열을 생성합니다
const arr = new Array(1, 2, 3);
console.log(arr); // [1, 2, 3]
  • push(): 배열의 끝에 요소를 추가합니다
const fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
  • pop(): 배열의 마지막 요소를 제거하고 반환합니다
const fruits = ["apple", "banana", "orange"];
const lastFruit = fruits.pop();
console.log(lastFruit); // "orange"
  • shift(): 배열의 첫 번째 요소를 제거하고 반환합니다
const fruits = ["apple", "banana", "orange"];
const firstFruit = fruits.shift();
console.log(firstFruit); // "apple"
  • unshift(): 배열의 시작에 요소를 추가합니다
const fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "orange"]
  • slice(): 배열의 일부분을 복사하여 새로운 배열을 반환합니다
const fruits = ["apple", "banana", "orange"];
const citrus = fruits.slice(1, 3);
console.log(citrus); // ["banana", "orange"]
  • splice(): 배열의 요소를 추가 또는 제거합니다
const fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1, "kiwi");
console.log(fruits); // ["apple", "kiwi", "orange"]
  • forEach(): 배열의 각 요소에 대해 함수를 실행합니다
const fruits = ["apple", "banana", "orange"];
fruits.forEach((fruit) => console.log(fruit));
// apple
// banana
// orange

🔎 Set 객체

  • Set(): 중복을 허용하지 않는 값을 저장하는 객체를 생성합니다
const uniqueNumbers = new Set([1, 2, 2, 3]);
console.log(uniqueNumbers); // Set { 1, 2, 3 }
  • add(value): Set에 값을 추가합니다
const uniqueNumbers = new Set();
uniqueNumbers.add(1);
uniqueNumbers.add(2);
console.log(uniqueNumbers); // Set { 1, 2 }
  • delete(value): Set에서 값을 제거합니다
const uniqueNumbers = new Set([1, 2, 3]);
uniqueNumbers.delete(2);
console.log(uniqueNumbers); // Set { 1, 3 }
  • has(value): Set에 특정 값이 있는지 확인합니다
const uniqueNumbers = new Set([1, 2, 3]);
console.log(uniqueNumbers.has(2)); // true
  • clear(): Set의 모든 요소를 제거합니다
const uniqueNumbers = new Set([1, 2, 3]);
uniqueNumbers.clear();
console.log(uniqueNumbers); // Set {}

🔎 Map 객체

  • Map(): 키-값 쌍을 저장하는 객체를 생성합니다
const map = new Map();
map.set("name", "Alice");
console.log(map); // Map { "name" => "Alice" }
  • set(key, value): Map에 키와 값을 추가합니다
const map = new Map();
map.set("name", "Alice");
map.set("age", 25);
console.log(map); // Map { "name" => "Alice", "age" => 25 }
  • get(key): Map에서 키에 해당하는 값을 반환합니다
const map = new Map();
map.set("name", "Alice");
console.log(map.get("name")); // "Alice"
  • delete(key): Map에서 특정 키-값 쌍을 제거합니다
const map = new Map([["name", "Alice"], ["age", 25]]);
map.delete("age");
console.log(map); // Map { "name" => "Alice" }
  • has(key): Map에 특정 키가 존재하는지 확인합니다
const map = new Map([["name", "Alice"]]);
console.log(map.has("name")); // true

📌 문자열 관련 메소드

🔎 String 객체

  • String(): 문자열을 생성합니다
const str = new String("Hello, World!");
console.log(str); // "Hello, World!"
  • charAt(index): 특정 인덱스의 문자를 반환합니다
const str = "Hello";
console.log(str.charAt(1)); // "e"
  • concat(): 문자열을 연결합니다
const str1 = "Hello, ";
const str2 = "World!";
console.log(str1.concat(str2)); // "Hello, World!"
  • indexOf(searchValue): 특정 문자열이 처음 나타나는 위치를 반환합니다
const str = "Hello, World!";
console.log(str.indexOf("World")); // 7
  • replace(searchValue, newValue): 문자열의 특정 부분을 교체합니다
const str = "Hello, World!";
console.log(str.replace("World", "JavaScript")); // "Hello, JavaScript!"
  • split(separator): 문자열을 나누어 배열로 반환합니다
const str = "apple,banana,orange";
const fruits = str.split(",");
console.log(fruits); // ["apple", "banana", "orange"]

📌 수학 관련 메소드

🔎 Math 객체

  • Math.abs(x): 절대값을 반환합니다
console.log(Math.abs(-5)); // 5
  • Math.ceil(x): 올림합니다
console.log(Math.ceil(4.2)); // 5
  • Math.floor(x): 내림합니다
console.log(Math.floor(4.8)); // 4
  • Math.max(): 최대값을 반환합니다
console.log(Math.max(1, 2, 3)); // 3
  • Math.min(): 최소값을 반환합니다
console.log(Math.min(1, 2, 3)); // 1
  • Math.random(): 0과 1 사이의 난수를 생성합니다
console.log(Math.random()); // 0과 1 사이의 난수

📌 날짜 및 시간 관련 메소드

🔎 Date 객체

  • Date(): 현재 날짜와 시간을 생성합니다
const now = new Date();
console.log(now); // 현재 날짜와 시간
  • getFullYear(): 연도를 반환합니다
const now = new Date();
console.log(now.getFullYear()); // 현재 연도
  • getMonth(): 월을 반환합니다 (0부터 시작)
const now = new Date();
console.log(now.getMonth()); // 현재 월 (0부터 시작)
  • getDate(): 날짜를 반환합니다
const now = new Date();
console.log(now.getDate()); // 현재 날짜
  • getDay(): 요일을 반환합니다 (0=일요일)
const now = new Date();
console.log(now.getDay()); // 현재 요일 (0=일요일)
  • getTime(): 1970년 1월 1일 00:00:00 UTC로부터의 밀리초를 반환합니다.
const now = new Date();
console.log(now.getTime()); // 1970년 1월 1일 00:00:00 UTC로부터의 밀리초
  • setFullYear(year): 연도를 설정합니다
const now = new Date();
now.setFullYear(2025);
console.log(now); // 연도가 2025로 설정된 날짜
  • getMonth(): 월을 반환합니다 (0부터 시작)
const now = new Date();
console.log(now.getMonth()); // 9 (10월)
  • getDate(): 날짜를 반환합니다
const now = new Date();
console.log(now.getDate()); // 6 (예시)
  • getHours(): 시간을 반환합니다
const now = new Date();
console.log(now.getHours()); // 14 (예시)
  • getMinutes(): 분을 반환합니다

const now = new Date();
console.log(now.getMinutes()); // 30 (예시)
  • getSeconds(): 초를 반환합니다.
const now = new Date();
console.log(now.getSeconds()); // 45 (예시)

📌 JSON 관련 메소드

  • JSON.stringify(value): JavaScript 객체를 JSON 문자열로 변환합니다
const obj = { name: "Alice", age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"Alice","age":25}'
  • JSON.parse(json): JSON 문자열을 JavaScript 객체로 변환합니다
const jsonString = '{"name":"Alice","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj); // { name: "Alice", age: 25 }

📌 DOM 관련 메소드

  • document.getElementById(id): ID로 요소를 선택합니다
const element = document.getElementById("myElement");
console.log(element); // 해당 ID를 가진 요소
  • document.getElementsByClassName(className): 클래스 이름으로 요소를 선택합니다
const elements = document.getElementsByClassName("myClass");
console.log(elements); // 해당 클래스 이름을 가진 모든 요소 (HTMLCollection)
  • document.querySelector(selector): CSS 선택자로 요소를 선택합니다
const element = document.querySelector(".myClass");
console.log(element); // 첫 번째로 찾은 클래스가 "myClass"인 요소
  • document.createElement(tagName): 새로운 HTML 요소를 생성합니다
const newDiv = document.createElement("div");
newDiv.textContent = "안녕하세요!";
document.body.appendChild(newDiv); // 새로운 div 요소를 body에 추가
  • element.appendChild(child): 자식 요소를 추가합니다
const parent = document.getElementById("parentElement");
const child = document.createElement("p");
child.textContent = "이것은 자식 요소입니다.";
parent.appendChild(child); // 부모 요소에 자식 요소 추가
  • element.removeChild(child): 자식 요소를 제거합니다
const parent = document.getElementById("parentElement");
const child = document.getElementById("childElement");
parent.removeChild(child); // 부모 요소에서 자식 요소 제거
  • element.setAttribute(attributeName, value): 요소의 속성을 설정합니다
const link = document.createElement("a");
link.setAttribute("href", "https://example.com");
link.textContent = "예제 링크";
document.body.appendChild(link); // 링크 요소를 body에 추가
  • element.classList.add(className): 요소에 클래스를 추가합니다
const element = document.getElementById("myElement");
element.classList.add("active"); // "active" 클래스를 추가

📌 이벤트 관련 함수 및 메소드

🔎 이벤트 리스너 추가

  • addEventListener(type, listener): 지정한 이벤트가 발생했을 때 호출될 함수를 추가합니다
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
  alert("Button clicked!");
});

🔎 이벤트 리스너 제거

  • removeEventListener(event, callback):이벤트 리스너를 제거합니다
button.removeEventListener("click", handleClick);

🔎 이벤트 객체

  • event: 이벤트가 발생할 때 자동으로 전달되는 객체로, 이벤트에 대한 정보를 포함합니다
const button = document.getElementById("myButton");
button.addEventListener("click", (event) => {
  console.log(event); // 이벤트 객체 정보 출력
});

🔎 이벤트 전파 제어

event.stopPropagation(): 이벤트가 상위 요소로 전파되는 것을 막습니다

const parent = document.getElementById("parent");
const child = document.getElementById("child");

parent.addEventListener("click", () => {
  alert("Parent clicked!");
});

child.addEventListener("click", (event) => {
  event.stopPropagation(); // 부모 요소로의 전파를 막음
  alert("Child clicked!");
});
  • event.preventDefault(): 기본 동작을 취소합니다
    예를 들어, 링크 클릭 시 페이지 이동을 방지할 수 있습니다
const link = document.getElementById("myLink");
link.addEventListener("click", (event) => {
  event.preventDefault(); // 링크 클릭 시 기본 동작 방지
  alert("Link clicked, but no navigation!");
});

🔎 이벤트 전파 흐름

  • 캡처링(Capturing): 이벤트가 최상위 요소에서 하위 요소로 전파됩니다
  • 버블링(Bubbling): 하위 요소에서 최상위 요소로 이벤트가 전파됩니다

🔎 이벤트 속성

  • event.target: 이벤트가 발생한 요소를 반환합니다

const button = document.getElementById("myButton");
button.addEventListener("click", (event) => {
  console.log(event.target); // 클릭한 버튼 요소 출력
});
  • event.currentTarget: 이벤트 리스너가 등록된 요소를 반환합니다
const parent = document.getElementById("parent");
parent.addEventListener("click", (event) => {
  console.log(event.currentTarget); // 항상 parent 요소 출력
});

🔎 다양한 이벤트 유형

  • click: 마우스 클릭 이벤트
  • mouseover: 마우스가 요소 위로 이동할 때 발생
  • mouseout: 마우스가 요소에서 나갈 때 발생
  • keydown: 키보드 키가 눌릴 때 발생
  • keyup: 키보드 키에서 손을 뗄 때 발생
  • keypress: 문자를 입력할 때 발생
  • focus: 요소가 포커스를 받을 때 발생합니다
  • blur: 요소가 포커스를 잃을 때 발생합니다
  • change: 입력 요소의 값이 변경되었을 때 발생합니다
  • input: 입력 필드에서 값이 변경될 때마다 발생합니다
  • submit: 폼이 제출될 때 발생합니다

🔎 이벤트 Delegation

  • 부모 요소에서 자식 요소의 이벤트를 관리하는 방식입니다 동적으로 추가된 요소에도 이벤트가 적용됩니다
const parent = document.getElementById("parent");

parent.addEventListener("click", (event) => {
  if (event.target.matches(".child")) {
    alert("Child clicked!");
  }
});

📌 이벤트 리스너에서 this 사용

  • 이벤트 리스너 내에서 this는 이벤트가 발생한 요소를 참조합니다
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
  console.log(this); // 클릭한 버튼 요소를 출력
});

📌 비동기 처리 관련 메소드

  • Promise(): 비동기 작업의 성공 또는 실패를 나타내는 객체입니다
    비동기 작업이 완료되면 결과를 처리하는 방법을 제공합니다
const myPromise = new Promise((resolve, reject) => {
  const success = true; // 성공 여부를 설정

  if (success) {
    resolve("작업이 성공했습니다!"); // 성공 시 호출
  } else {
    reject("작업이 실패했습니다!"); // 실패 시 호출
  }
});

myPromise
  .then((message) => console.log(message)) // 성공 시 실행
  .catch((error) => console.error(error)); // 실패 시 실행
  • async/await: 비동기 함수를 더 쉽게 작성할 수 있도록 도와줍니다
    async로 정의된 함수 안에서는 await를 사용하여 Promise의 결과를 기다릴 수 있습니다
async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts"); // 데이터 가져오기
    const data = await response.json(); // JSON 형태로 변환
    console.log(data); // 데이터를 출력
  } catch (error) {
    console.error("데이터를 가져오는 데 실패했습니다:", error); // 에러 처리
  }
}

fetchData(); // 비동기 데이터 가져오기 실행

📌 AJAX 요청 예시

  • AJAX(Asynchronous JavaScript and XML)는 웹 페이지가 전체를 새로 고치지 않고도 서버와 데이터를 교환할 수 있도록 해주는 기술입니다
  • XMLHttpRequest 객체를 사용하여 비동기 요청을 보낼 수 있습니다
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true); // GET 요청 초기화

xhr.onload = () => {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(JSON.parse(xhr.responseText)); // 요청 성공 시 데이터 출력
  } else {
    console.error(`요청 실패: ${xhr.status}`); // 에러 처리
  }
};

xhr.onerror = () => {
  console.error("네트워크 오류 발생"); // 네트워크 오류 처리
};

xhr.send(); // 요청 전송

📌 Fetch API 사용 예시

  • Fetch API는 더 간결하고 사용하기 쉬운 방식으로 네트워크 요청을 다룰 수 있게 합니다
  • Promise 기반으로 동작하므로 비동기 처리를 쉽게 할수 있습니다
fetch("https://jsonplaceholder.typicode.com/posts") // 데이터 요청
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`); // 에러 처리
    }
    return response.json(); // JSON 형태로 변환
  })
  .then(data => console.log(data)) // 데이터 출력
  .catch(error => console.error("데이터를 가져오는 데 실패했습니다:", error)); // 에러 처리


profile

0개의 댓글