
const obj = new Object();
obj.name = "John";
console.log(obj); // { name: "John" }
const person = { name: "Alice" };
console.log(person.hasOwnProperty("name")); // true
const person = { name: "Alice", age: 25 };
console.log(Object.keys(person)); // ["name", "age"]
const person = { name: "Alice", age: 25 };
console.log(Object.values(person)); // ["Alice", 25]
const greet = new Function("name", "return `Hello, ${name}!`;");
console.log(greet("Alice")); // "Hello, Alice!"
function greet() {
return `Hello, ${this.name}!`;
}
const person = { name: "Alice" };
console.log(greet.call(person)); // "Hello, Alice!"
function sum(a, b) {
return a + b;
}
console.log(sum.apply(null, [5, 10])); // 15
const arr = new Array(1, 2, 3);
console.log(arr); // [1, 2, 3]
const fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
const fruits = ["apple", "banana", "orange"];
const lastFruit = fruits.pop();
console.log(lastFruit); // "orange"
const fruits = ["apple", "banana", "orange"];
const firstFruit = fruits.shift();
console.log(firstFruit); // "apple"
const fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "orange"]
const fruits = ["apple", "banana", "orange"];
const citrus = fruits.slice(1, 3);
console.log(citrus); // ["banana", "orange"]
const fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1, "kiwi");
console.log(fruits); // ["apple", "kiwi", "orange"]
const fruits = ["apple", "banana", "orange"];
fruits.forEach((fruit) => console.log(fruit));
// apple
// banana
// orange
const uniqueNumbers = new Set([1, 2, 2, 3]);
console.log(uniqueNumbers); // Set { 1, 2, 3 }
const uniqueNumbers = new Set();
uniqueNumbers.add(1);
uniqueNumbers.add(2);
console.log(uniqueNumbers); // Set { 1, 2 }
const uniqueNumbers = new Set([1, 2, 3]);
uniqueNumbers.delete(2);
console.log(uniqueNumbers); // Set { 1, 3 }
const uniqueNumbers = new Set([1, 2, 3]);
console.log(uniqueNumbers.has(2)); // true
const uniqueNumbers = new Set([1, 2, 3]);
uniqueNumbers.clear();
console.log(uniqueNumbers); // Set {}
const map = new Map();
map.set("name", "Alice");
console.log(map); // Map { "name" => "Alice" }
const map = new Map();
map.set("name", "Alice");
map.set("age", 25);
console.log(map); // Map { "name" => "Alice", "age" => 25 }
const map = new Map();
map.set("name", "Alice");
console.log(map.get("name")); // "Alice"
const map = new Map([["name", "Alice"], ["age", 25]]);
map.delete("age");
console.log(map); // Map { "name" => "Alice" }
const map = new Map([["name", "Alice"]]);
console.log(map.has("name")); // true
const str = new String("Hello, World!");
console.log(str); // "Hello, World!"
const str = "Hello";
console.log(str.charAt(1)); // "e"
const str1 = "Hello, ";
const str2 = "World!";
console.log(str1.concat(str2)); // "Hello, World!"
const str = "Hello, World!";
console.log(str.indexOf("World")); // 7
const str = "Hello, World!";
console.log(str.replace("World", "JavaScript")); // "Hello, JavaScript!"
const str = "apple,banana,orange";
const fruits = str.split(",");
console.log(fruits); // ["apple", "banana", "orange"]
console.log(Math.abs(-5)); // 5
console.log(Math.ceil(4.2)); // 5
console.log(Math.floor(4.8)); // 4
console.log(Math.max(1, 2, 3)); // 3
console.log(Math.min(1, 2, 3)); // 1
console.log(Math.random()); // 0과 1 사이의 난수
const now = new Date();
console.log(now); // 현재 날짜와 시간
const now = new Date();
console.log(now.getFullYear()); // 현재 연도
const now = new Date();
console.log(now.getMonth()); // 현재 월 (0부터 시작)
const now = new Date();
console.log(now.getDate()); // 현재 날짜
const now = new Date();
console.log(now.getDay()); // 현재 요일 (0=일요일)
const now = new Date();
console.log(now.getTime()); // 1970년 1월 1일 00:00:00 UTC로부터의 밀리초
const now = new Date();
now.setFullYear(2025);
console.log(now); // 연도가 2025로 설정된 날짜
const now = new Date();
console.log(now.getMonth()); // 9 (10월)
const now = new Date();
console.log(now.getDate()); // 6 (예시)
const now = new Date();
console.log(now.getHours()); // 14 (예시)
const now = new Date();
console.log(now.getMinutes()); // 30 (예시)
const now = new Date();
console.log(now.getSeconds()); // 45 (예시)
const obj = { name: "Alice", age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"Alice","age":25}'
const jsonString = '{"name":"Alice","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj); // { name: "Alice", age: 25 }
const element = document.getElementById("myElement");
console.log(element); // 해당 ID를 가진 요소
const elements = document.getElementsByClassName("myClass");
console.log(elements); // 해당 클래스 이름을 가진 모든 요소 (HTMLCollection)
const element = document.querySelector(".myClass");
console.log(element); // 첫 번째로 찾은 클래스가 "myClass"인 요소
const newDiv = document.createElement("div");
newDiv.textContent = "안녕하세요!";
document.body.appendChild(newDiv); // 새로운 div 요소를 body에 추가
const parent = document.getElementById("parentElement");
const child = document.createElement("p");
child.textContent = "이것은 자식 요소입니다.";
parent.appendChild(child); // 부모 요소에 자식 요소 추가
const parent = document.getElementById("parentElement");
const child = document.getElementById("childElement");
parent.removeChild(child); // 부모 요소에서 자식 요소 제거
const link = document.createElement("a");
link.setAttribute("href", "https://example.com");
link.textContent = "예제 링크";
document.body.appendChild(link); // 링크 요소를 body에 추가
const element = document.getElementById("myElement");
element.classList.add("active"); // "active" 클래스를 추가
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
button.removeEventListener("click", handleClick);
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!");
});
const link = document.getElementById("myLink");
link.addEventListener("click", (event) => {
event.preventDefault(); // 링크 클릭 시 기본 동작 방지
alert("Link clicked, but no navigation!");
});
const button = document.getElementById("myButton");
button.addEventListener("click", (event) => {
console.log(event.target); // 클릭한 버튼 요소 출력
});
const parent = document.getElementById("parent");
parent.addEventListener("click", (event) => {
console.log(event.currentTarget); // 항상 parent 요소 출력
});
const parent = document.getElementById("parent");
parent.addEventListener("click", (event) => {
if (event.target.matches(".child")) {
alert("Child clicked!");
}
});
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log(this); // 클릭한 버튼 요소를 출력
});
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 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(); // 비동기 데이터 가져오기 실행
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("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)); // 에러 처리