🔗 map 함수
배열(리스트)을 전체 순환하면서 주어진 콜백함수를 통해 새로운 배열을 생성하는 함수
let arr = [10, 20, 30, 40, 50];
// map 함수의 콜백함수의 인자는 value, index, array 순서로 들어옴
// 각 값의 이름은 정해져있지 않으므로 임의로 설정 가능
arr.map((v) => {}); // value값만 가져옴
arr.map((v, idx) => {}); // value, index 값만 가져옴
arr.map((v, idx, array) => {}); // value, index, array 모두 가져옴
const arr = [1, 2, 3, 4, 5];
// 함수 내용이 한줄이면 중괄호와 return 생략 가능
const arr2 = arr.map((item) => item * 2); // [2, 4, 6, 8, 10]
// 아래와 같이 모든 value에 대해 수행하고자 하는 함수 하나만 넘겨줘도 가능
const arr3 = arr.map(String); // ["1", "2", "3", "4", "5"]
🌱 활용: 객체에서 특정 값만 추출
const users = [
{ id: 1, name: "hong" },
{ id: 1, name: "park" },
{ id: 1, name: "kim" },
];
const userNames = users.map((user) => user.name);
console.log(userNames); // ["hong", "park", "kim"]
🔗 reduce 함수
배열의 각 요소를 순회하면서 누적 값을 계산하는 함수
const nums = [1, 2, 3, 4, 5];
let total = 0;
// total: 이전값, 누적값
// v: 현재값
const sum = nums.reduce((total, v) => (total += v));
console.log(sum); // 15
// 아래와 같이 두번째 인자로 누적값의 초기값을 설정할 수 있음
const sum2 = nums.reduce((tot, v) => (tot += v), 0);
console.log(sum2); // 15
🌱 활용1: 최대값 구하기
const nums = [1, 2, 3, 4, 5];
const max = nums.reduce((m, v) => (v > m ? v : m), -1);
console.log(max); // 5
🌱 활용2: 개수 구하기
const alpha = ["a", "a", "b", "b", "c", "c", "c"];
const count = alpha.reduce((cnt_arr, v) => {
if (cnt_arr[v]) cnt_arr[v] += 1;
else cnt_arr[v] = 1;
return cnt_arr;
}, {});
console.log(count); // { a: 2, b: 2, c: 3}
🔗 find, filter 함수
🧩 find
특정 값을 찾아내는 것으로, 반환값은 특정 값이나 undefined
let f_arr = [1, 2, 3, 4, 5];
const n = f_arr.find((v, idx, arr) => {
return v < 3;
});
console.log(n); // 1 - 만족하는 값 하나만 반환, 없는 경우 undefined
🧩 filter
특정 요소를 걸러내는 것으로, 반환값은 배열 or 빈 배열
let f_arr = [1, 2, 3, 4, 5];
const res = f_arr.filter((v, idx, arr) => {
return v < 3;
});
console.log(res); // [1, 2] - 만족하는 값들로 이루어진 배열, 없는 경우 빈배열
🔗 JS 내장객체
🧩 window : 웹브라우저 창(화면) 제어
// 새 창 열기
window.open("https://www.naver.com");
// 팝업창 열기
window.open("https://www.google.com", "pop-up", "width=1000,height=800");
🧩 document : DOM(Document Object Model)을 제어
DOM - 웹브라우저가 html 문서를 로딩(분석)한 후 트리 모양으로 관리하는 데이터 구조 또는 객체
🫧 문서 객체 선택
- id로 선택 -
getElementById()
- class로 선택 :
getElementsClassName()
- tag로 선택 :
getElementsByTagName()
- css 선택자로 선택 :
querySelector()
,querySelectorAll()
<body>
<h1 id="header1">제목태그 1</h1>
<h1 id="header2">제목태그 2</h1>
<h2 class="header-h2">제목태그 3</h2>
<h2 class="header-h2">제목태그 4</h2>
<h2 class="header-h2">제목태그 5</h2>
<p>문단태그 p</p>
<p>문단태그 p</p>
<p>문단태그 p</p>
<script>
let h1 = document.getElementById("header1"); // id가 header1인 객체 선택
let h2 = document.getElementsByClassName("header-h2"); // 모든 header-h2 클래스 객체 선택
let p = document.getElementsByTagName("p"); // 모든 p 태그 선택
let first_h2 = document.querySelector(".header-h2"); // 첫번째 h2 선택
let all_h2 = document.querySelectorAll(".header-h2"); // 모든 header-h2 클래스 객체 선택
</script>
</body>
JS는 인터프리터 언어이므로 이와 같이 각 요소들이 로드된 후에 DOM 선택이 가능하므로 위와 같이 </body> 바로 위에서 DOM을 선택을 해야함
🙋🏻 만약 <head>
에서 DOM 선택을 하고 싶다면?
아래와 같이 window.onload를 활용
window.onload - 웹 페이지의 모든 요소가 완전히 로드된 후에 실행되는 JavaScript 이벤트 핸들러
<head>
<script>
window.onload = () => {
// 페이지가 로드된 후 실행할 코드
let h1 = document.getElementById("header1");
let h2 = document.getElementsByClassName("header-h2");
let p = document.getElementsByTagName("p");
let first_h2 = document.querySelector(".header-h2");
let all_h2 = document.querySelectorAll(".header-h2");
};
</script>
</head>
🫧 innerText, innerHTML
<body>
<h1 id="id1">innerHTML의 내용</h1>
<h1 id="id2">innerText의 내용</h1>
<script>
const header1 = document.getElementById("id1");
header1.innerHTML = "<ins>변경된 내용</ins>"; // id1 헤더의 내용이 밑줄 그어진 "변경된 내용"이라는 텍스트로 변경됨
const header2 = document.getElementById("id2");
header2.innerText = "<ins>변경된 내용</ins>"; // id2 헤더의 내용이 "<ins>변경된 내용</ins>"로 변경됨
</script>
</body>
🫧 setAttribute, getAttribute
<script>
function changeImg() {
// img 요소의 src값을 불러온 후(getAttribute) 비교
if (img.getAttribute("src") === "./img/apple.png") {
// img 요소의 src값 변경(setAttribute)
img.setAttribute("src", "./img/dog.png");
} else {
img.setAttribute("src", "./img/apple.png");
}
}
window.onload = () => {
let img = document.getElementById("img");
};
</script>
.
.
.
<body>
<button onclick="changeImg()">이미지 변경하기</button>
</body>
🫧 classList의 add, remove, contains
<style>
.active {
background-color: aqua;
font-size: 24px;
}
.select {
color: red;
border: 2px solid blue;
}
</style>
<script>
function func1() {
// header 요소의 클래스에 "active"가 포함되어있는지 확인
if (header.classList.contains("active"))
// header 요소의 클래스에서 "active" 제거
header.classList.remove("active");
// header 요소의 클래스에서 "active" 추가
else header.classList.add("active");
}
function func2() {
// header 요소의 클래스에 "select"가 포함되어있는지 확인
if (header.classList.contains("select"))
// header 요소의 클래스에서 "select" 제거
header.classList.remove("select");
// header 요소의 클래스에서 "select" 추가
else header.classList.add("select");
}
window.onload = () => {
let header = document.getElementById("header");
};
</script>
.
.
.
<body>
<h1 id="header" class="">액티브 셀렉트</h1>
<button onclick="func1();">액티브 Active</button>
<button onclick="func2();">셀렉트 Select</button>
</body>
🫧 addEventListener
DOM 요소에 이벤트를 등록하기 위해 사용하는 메서드
let btn = document.getElementById("btn");
// btn 요소를 클릭하면 "btn 클릭" 출력
btn.addEventListener("click", ()=>console.log("btn 클릭"});
🐭 mouse event
click
: 클릭할 때 발생dblclick
: 더블 클릭할 때 발생mouseover
: 마우스가 요소 위로 올라갈 때 발생mouseout
: 마우스가 요소에서 벗어날 때 발생mousedown
: 마우스를 누를 때 발생mouseup
: 마우스를 뗄 때 발생mousemove
: 마우스를 움직일 때 발생
⌨️ keyboard event
keydown
: 키를 누를 때 발생keyup
: 키를 뗄 때 발생keypress
: 키를 누르고 있을 때 발생
📋 form event
submit
: 폼이 제출될 때 발생focus
: 요소에 포커스가 잡힐 때 발생blur
: 요소에서 포커스가 벗어날 때 발생change
: 입력값이 변경되었을 때 발생input
: 사용자가 입력할 때마다 발생
🪟 window event
load
: 페이지나 리소스가 완전히 로드되었을 때 발생resize
: 브라우저 창 크기가 변경될 때 발생scroll
: 사용자가 스크롤할 때 발생unload
: 사용자가 페이지를 떠날 때 발생
📱 touch event(mobile)
touchstart
: 화면을 터치했을 때 발생touchend
: 터치가 끝날 때 발생touchmove
: 터치한 채로 움직일 때 발생
🫧 location : 페이지주소(URL) 제어
🌱 페이지이동
- Redirect - 사이트간의 이동, 내부 데이터(세션)을 버리고 이동
- location(GET), a 태그(GET), meta refresh(GET) - forward - 내부 페이지간의 이동, 내부 데이터(세션)을 가지고 이동
// location 객체를 통한 페이지 이동
location.href = "https://www.google.com";
location = "https://www.google.com"; // 이렇게도 가능
// 아래와 같이도 활용 가능
<button type="button" onclick="location.href='https://www.google.com'">
페이지이동
</button>
🧩 Etc...
🫧 history : 페이지 방문 기록 제어
🫧 console : 로그 메시지를 생성, 저장, 관리하는 과정을 제어
🫧 navigator : 웹브라우저와 사용자 시스템 정보
🫧 fetch : HTTP 통신, ES6의 내장함수 - 비슷한 기능을 하는 라이브러리: axios, jQuery, ajax
✈️ 출처
한국경제신문 x 토스뱅크 풀스택 훈련
'언어 > Javascript' 카테고리의 다른 글
Javascript 파헤치기 4번째 - ES6 문법 (1) | 2025.01.21 |
---|---|
Javascript 파헤치기 3번째 (1) | 2025.01.20 |
Javascript 파헤치기 2번째 (2) | 2025.01.17 |
Javascript 파헤치기 1번째 (1) | 2025.01.16 |