
이번에도 Array Cardio Day 1과 같이 배열메서드에 관한 연습이 주인 회차이다
직접 배열메서드를 사용해보면서 더욱 더 익숙해져 볼 수 있도록하자!
script 내부에 people이라는 배열과 comments라는 배열이 할당되어있는 상태이다<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Array Cardio 💪💪</title>
<link rel="icon" href="https://fav.farm/🔥" />
</head>
<body>
<p><em>Psst: have a look at the JavaScript Console</em> 💁</p>
<script>
// ## Array Cardio Day 2
const people = [
{ name: 'Wes', year: 1988 },
{ name: 'Kait', year: 1986 },
{ name: 'Irv', year: 1970 },
{ name: 'Lux', year: 2015 }
];
const comments = [
{ text: 'Love this!', id: 523423 },
{ text: 'Super good', id: 823423 },
{ text: 'You are the best', id: 2039842 },
{ text: 'Ramen is my fav food ever', id: 123523 },
{ text: 'Nice Nice Nice!', id: 542328 }
];
// Some and Every Checks
// Array.prototype.some() // is at least one person 19 or older?
// Array.prototype.every() // is everyone 19 or older?
// Array.prototype.find()
// Find is like filter, but instead returns just the one you are looking for
// find the comment with the ID of 823423
// Array.prototype.findIndex()
// Find the comment with this ID
// delete the comment with the ID of 823423
</script>
</body>
</html>
Array.prototype.some()이란?
배열 안에 어떤 요소라도 주어진 판별 함수를 적어도 하나라도 통과하는지 여부(불리언으로 반환)
is at least one person 19 or older?
const isAdult = people.some(function (person) {
const currentYear = new Date().getFullYear();
if (currentYear - person.year >= 19) {
return true;
}
});
isAdult라는 변수에 peopleArray의 some메서드를 사용하는데 콜백함수로 person이라는 매개변수를 전달받고 있다. new Date()로 현재 시간을 받아온 후getFullYear()로 현재 년도를 받아온다
new Date().getFullYear
currentYear(=2023)에서 person.year(1988, 1986 등등..)을 뺀 값이 19와 같거나 크면 true를 반환한다isAdult 리팩토링
some() 자체가 리턴값으로 true 나 false를 반환하기 때문에, 위 코드처럼 굳이 true를 명시적으로 작성할 필요가 없기때문에const is_adult = people.some((person) => new Date().getFullYear() - person.year >= 19);
console.log(is_adult) //person.year이 19보다 큰거나 같은 경우가 하나라도 존재하므로 true를 반환
Array.every()란?
배열안의 모든 요소가 주어진 판별함수(콜백함수)를 통과하는지의 여부 (이것또한 Boolean 값 반환)
is everyone 19 or older?
people.year이 19살 이상인가? const allAudlts = people.every((person) => new Date().getFullYear() - person.year >= 19);
console.log(allAudlts); // person.year이 19보다 작은 경우도 있으므로 false를 반환
❓
Array.prototype.find()란?
주어진 판별함수(콜백함수)에서 만족하는 첫번째 요소의 값을 반환
Find is like filter, but instead returns just the one you are looking for
find the comment with the ID of 823423
find()메서드는 array.filter()와 비슷하지만, 대신 찾고 있는 것 하나만 반환한다
ID가 823423인 댓글 찾기
const commnet = comments.find((comment) => {
if (comment.id === 823423) {
return true;
}
});
console.log(commnet); // 하단이미지 object

id가 823423인 comments를 찾아서 객체로 리턴하는 모습
Array.find()또한 if문이나 return값 필요없이 바로 값을 찾을 수 있다
const comment = comments.find((commnet) => comment.id === 823423);
console.log(commnet); // 위 코드와 동일한 객체 출력
❓
Array.prototype.findIndex()란?
주어진 판별 함수(콜백함수)를 만족하는 배열의 첫번째 요소에 대한 인덱스를 리턴 만족하지않는다면 -1를 리턴한다
이 ID의 댓글 찾기
const index = comments.findIndex((comment) => comment.id === 823423);
console.log(index); // comments 배열의 두번째에 위치해있으므로 1을 반환
ID가 823423인 댓글 삭제
❓
Array.prototype.slice()란?
기존 배열의 일부를 추출하여, 이를 다시 새로운 배열객체로 만든다.
array.slice(start,end)-->end생략시 배열의 마지막까지 추출
const fruits = ['apple', 'banana', 'cherry', 'orange', 'lemon'];
const citrus = fruits.slice(3);
// end값이 생략되었으므로 orange(index 3)부터 ~ lemon(끝 index)까지 추출해 새로운 배열객체로 반환
console.log(citrus); // ['orange', 'lemon']
// 1~3까지 추출해 새로운배열객체로 반환 여기서 end값인 3(인덱스)는 생략된다
// 따라서 index 1,2인 'banna'와 'cheery' 를 추출해 새로운 배열로 반환된다
const berries = fruits.slice(1, 3);
console.log(berries); // ['banana', 'cherry']
(0, index(===1))index는 1이므로 0부터~1까지 즉 0번째 index인{text: "Love this!", id: 523423} 가 반환된다(index + 1 (===2)){text: "You are the best", id: 2039842},{text: "Ramen is my fav food ever", id: 123523},{text: "Nice Nice Nice!", id: 542328},spread operator로 전개시킨다 const newComments = [...comments.slice(0, index), ...comments.slice(index + 1)];
console.log(newComments);

slice로 추출해낸 새로운 두개의 객체배열을 spread operator로 전개한 모습