티스토리 뷰
배열 반복(Array Iteration)
1. forEach()
배열명.forEach(함수)
배열이 가지고 있는 함수(메소드)로써 단순하게 배열 내부의 요소를 사용해 콜백함수를 호출
형식)
배열명.forEach(콜백함수)
배열명.forEach(function(value, index, array){
함수 실행문
});
배열명.forEach((value, index, array)=>{
함수 실행문
});
배열명.forEach((value)=>{
함수 실행문
});
매개변수인 value, index, array 중 index와 array는 생략 가능, 필요할 경우만 순서 맞춰 사용
value, index 대신 임의의 변수명 사용가능
<script>
const array=[23,96,5,73];
array.forEach((number, index, array)=>{
document.write("number :" + number+"<br>");
document.write("index :" + index+"<br>");
});
</script>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener("DOMContentLoaded", function (){
const div = document.querySelector("#content")
let text ="";
const array=[25,30,55,79];
array.forEach((number, index)=>{
// document.write("number :" + number+"<br>");
// document.write("index :" + index+"<br>");
text +=`<h2> index : ${index}, number : ${number} </h2>`;
});
div.innerHTML = text;
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
2. map()
● 각 배열 요소에 함수를 수행하여 새로운 배열을 생성함,따라서 변수에 저장 함
● 값이 없는 배열 요소에 대해서는 함수를 실행하지 않음
● 원본 배열을 변경하지 않음
형식)배열명.map(콜백함수)
let 리턴값저장할변수명 = 배열명.map(function(value, index, array){
실행문
return 리턴값;
});
let 리턴값저장할변수명 = 배열명.map((value, index, array)=>{
실행문
return 리턴값;
});
let 리턴값저장할변수명 = 배열명.map((value, index)=>{
실행문
return 리턴값;
});
let 리턴값저장할변수명 = 배열명.map((value)=>{
실행문
return 리턴값;
});
매개변수인 value, index, array 중 index와 array는 생략 가능, 필요할 경우만 순서 맞춰 사용
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener("DOMContentLoaded", function (){
const div = document.querySelector("#content")
const map_test = Array(5).fill(3).map((v, i, array)=>{return (2*i + v)});
div.textContent = map_test;
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
//3,5,7,9,11
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener("DOMContentLoaded", function (){
const div = document.querySelector("#content")
const numbers = [25, 35,75,60];
const result = numbers.map(myFunction);
function myFunction(value, index){
return value + 100;
}
div.textContent = result;
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
3. find()
● 콜백 함수의 반환값이 true인 요소를 찾는 메서드
● true인 요소가 여러 개일 경우에는 처음 찾은 요소를 반환
배열에서 30보다 큰 첫 번째 값 찾기
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener("DOMContentLoaded", function (){
const div = document.querySelector("#content")
const numbers = [25, 35,15,60];
const result = numbers.find(myFunction);
function myFunction(value, index){
return value > 30;
}
div.textContent = result; //35
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
4. findIndex()
● 찾은 요소의 인덱스를 반환
● 찾지 못했을 경우 -1을 반환
50보다 큰 자료 찾아 그것의 인덱스 가져오기
</html><!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener("DOMContentLoaded", function (){
const div = document.querySelector("#content")
const numbers = [25, 35,15,60];
const result = numbers.findIndex(myFunction);
function myFunction(value, index){
return value > 50;
}
div.textContent = result; //3
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
5. filter()
● callback function에서 return 하는 value가 true인 것들만 모아서 새로운 배열을 만드는 함수
● find()처럼 콜백 함수의 반환 값이 true가 되는 요소를 찾지만,
● 하나만 찾는 것이 아닌, 해당하는 모든 요소를 찾아 결과를 배열로 반환
● 즉,테스트를 통과하는 배열 요소로 새로운 배열을 생성
형식)
const 배열명 = [요소, 요소,...]
let new_배열명 = 배열명.filter((value, index, array) =>{
조건문을 포함한 실행문
return 값;
});
배열에서 30이상인 자료 찾아 배열 생성
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener("DOMContentLoaded", function (){
const div = document.querySelector("#content")
const numbers = [25, 35,15,60];
const result = numbers.filter(myFunction);
function myFunction(value, index){
return value > 30;
}
div.textContent = result; //35, 60
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
● 메서드 체이닝(method chaining)
어떤 메서드가 리턴하는 값을 기반으로 해서 함수를 줄줄이 사용하는 것
<script>
const numbers = [25,35,75,60];
//30이상인 것만 추출
const result = numbers.filter((value, index)=>{
return value>=30;
});
console.log(result);
// const num = [0,1,2,3,4,5,6,7,8,9];
// //1. filter()함수를 적용해서 짝수만 뽑기
// const even = num.filter((value)=>{
// return value % 2 === 0;
// });
// // console.log(even); //[0,2,4,6,8]
// //2. map()함수
// const even_power = even.map((value)=>{
// return value * value;
// });
// //console.log(even_power); //[0, 4, 16, 36, 64]
// //3. froEach()
// even_power.forEach((value)=>{
// console.log(value);
// });
//메서드 체이닝
const num = [0,1,2,3,4,5,6,7,8,9];
num
.filter((value)=> value % 2 === 0)
.map((value)=> value * value)
.forEach((value)=>{
console.log(value);
});
</script>
//----------------------------------------
<script>
const numbers = [0,1,2,3,4,5,6,7,8,9];
//배열의 메소드를 연속적으로 사용(method chaining)
numbers
.filter((value)=> value % 2 === 0)
.map((value)=>value * value)
.forEach((value)=>{
document.write(value + "<br>")
});
</script>
기타 메서드
1. toFixed(소수점출력할자릿수)
a = 123.45678
a.toFixed(2) → 124.45
2.Number.isNan()
NaN(Not a Number) : 자료형은 숫자인데 값이 숫자가 아닌 것
a = Number("hi")
Number.isNaN(a) → true
3. Number.isFinites()
문자열 함수
1. trim() : 문자열 양쪽 끝의 공백(줄바꿈,띄어쓰기) 없애기
2. split() : 문자열을 특정 기호로 자르기
a. 문자열.split("\n")
b. 문자열.split(",")
c. 문자열.split(" ")
'Front-End Programming > JavaScript' 카테고리의 다른 글
DOM(Document Object Model) (0) | 2025.03.23 |
---|---|
JSON (0) | 2025.03.22 |
객체(Object) (3) | 2025.03.22 |
함수(Function) (0) | 2025.03.18 |
배열(Array) (3) | 2025.03.18 |