일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- 부트캠프 취업후기
- Filter
- 프론트엔드부트캠프후기
- sqld 자격증 시험
- react hook
- 퍼블리셔 이직후기
- css 꿀팁
- firebase rules
- 국비지원취업
- reduce
- 성능개선
- foreach
- git
- TypeScript
- 프론트엔드개발자
- 야놀자 fe 1기
- js CRUD
- promise 비동기처리
- 패스트캠퍼스 부트캠프
- sqld 55회
- github
- Firebase
- 리액트오류
- 패스트캠퍼스
- Where
- 국비지원
- 야놀자x패스트캠퍼스
- 부트캠프
- 2024 sqld
- map
- Today
- Total
Tech is created to fix problem
배열&객체 연습문제 2 본문
Q1.
아래 배열에서 모든 사람들의 이름을 Park 으로 바꾸는 코드를 작성해주세요. (map 활용, spread 연산자 활용)
A1. 내가 푼 답
let students = [
{id: 1, name: 'Kim', score: {math: 50, english: 70}},
{id: 2, name: 'Kim', score: {math: 80, english: 60}},
{id: 3, name: 'Lee', score: {math: 70, english: 50}},
]
const newArray = students.map(student => ({...student, name : 'Park' }));
console.log(newArray);
Q2.
아래 배열에서 이름이 Kim 인 사람들을 찾고, score 에 science: 100, history: 100 을 추가해주세요. (filter, map 활용, spread 연산자 활용)
A2. 내가 푼 답
let students = [
{id: 1, name: 'Kim', score: {math: 50, english: 70, korean: 30, physics: 60}},
{id: 2, name: 'Kim', score: {math: 80, english: 60, korean: 40, physics: 40}},
{id: 3, name: 'Lee', score: {math: 70, english: 50, korean: 50, physics: 80}},
]
// 내가 낸 오류
// const modArray = newArray.map(item =>
//({...item, score.science:100, score.history:100})
//)
// 수정사항 (return 부분에 객체의 모양을 유지해줘야 덮어쓸 수 있음, 그리고 score 원본도 가져오려면 ...연산자 쓸 것)
// ...item,
// score: {
// ...item.score,
// science: 100,
// history: 100,
// }
// 정답
const newArray = students.filter(item => item.name == 'Kim');
const modArray = newArray.map(item => ({
...item,
score: {
...item.score,
science:100,
history:100,
}
}))
console.log(modArray);
Q3.
아래 배열에서, 학생 별로 score 객체 안에 sum: (점수 총합) 을 추가하는 코드를 작성하세요. (map, spread 연산자, 비구조할당 활용)
A3. 내가 푼 답
let students = [
{id: 1, name: 'Kim', score: {math: 50, english: 70}},
{id: 2, name: 'Park', score: {math: 80, english: 60}},
{id: 3, name: 'Lee', score: {math: 70, english: 50}},
]
const newarray = students.map(student => {
const {math, english} = student.score;
return {...student, score: {...student.score, sum: math + english}}
});
console.log(newarray);
Q4.
학생 수에 관계없이 아래와 같은 배열이 들어왔을 때 모든 점수의 총합을 구하는 함수를 작성하세요. (reduce, 비구조할당, spread, rest 연산자 활용)
A4. 내가 푼 답
let students = [
{id: 1, name: 'Kim', score: {math: 50, english: 70}},
{id: 2, name: 'Park', score: {math: 80, english: 60}},
{id: 3, name: 'Lee', score: {math: 70, english: 50}},
{id: 4, name: 'Choi', score: {math: 70, english: 50}},
]
const total = students.reduce((sum, cur) => {
const {math, english} = cur.score;
return sum + math + english;
}, 0);
console.log(total);
// rest를 사용해본다면? (아래처럼)
const sum = (...student) => {
return student.reduce((sum, current) => {
const {math, english} = current.score;
return sum + math + english;
}, 0)
};
const result = sum(...students);
console.log(result);
간단게임 만들기)
플레이어 간의 공격이 가능한 아주 간단한 게임을 만들려고 합니다.
플레이어는 hp, mp, ap (공격력) 이라는 스탯을 가지고 있고, 고유한 이름을 가지고 있습니다.
attack 이라는 행동을 수행하면 공격받은 대상 플레이어의 hp 가 공격한 플레이어의 ap 만큼 감소합니다.
heal 이라는 행동을 수행하면 행동을 수행한 플레이어의 mp 가 10만큼 감소하고, 그만큼 hp 가 증가합니다.
게임 자체적으로는 살아있는 (hp 가 0 이상인) 유저들의 이름만 출력하는 기능을 가지고 있습니다.
객체와 메소드를 활용해서 위와 같은 간단한 게임을 만들어보세요.
(플레이어 객체, 게임 객체 각각 만드는 것을 권장드립니다.)
A) 내가 푼 답
const VALUE = 10;
class game {
constructor(name,hp,mp,ap){
this.name = name;
this.hp = hp;
this.mp = mp;
this.ap = ap;
}
attack(target) {
this.ap -= VALUE;
target.hp -= VALUE;
}
heal() {
this.mp -= VALUE;
this.hp += VALUE;
}
}
const me = new game('furaha', 100, 100, 100);
const com = new game('computer', 100, 100, 100);
me.attack(com);
console.log(me);
console.log(com);
//다른 정답
const player = {
hp: 50,
mp: 50,
ap: 10,
attack: function(object){
object.hp = object.hp - this.ap;
},
heal: function(){
this.mp -= 10;
this.hp += 10;
}
}
const game = {
players: [
{
id: 1,
...player,
name: 'Kim'
},
{
id: 2,
...player,
name: 'Park'
}
],
getAlive: function() {
alives = this.players.filter((player) => player.hp > 0);
return alives.map((alive) => alive.name);
}
}
아직은 구조분해랑 전개연산자를 사용하는게 익숙하지가 않다,,!
무한 메소드 체이닝을 피하려면 구조분해 사용이 익숙해져야하고
코드를 간략화하기 위해서는 전개연산자를 적절히 사용해주어야한다!
'연습 또 연습 > js 연습문제' 카테고리의 다른 글
패스트캠퍼스X야놀자 프론트엔드 개발 부트캠프_클론과제 리팩토링 후기 (0) | 2023.08.07 |
---|---|
패스트캠퍼스X야놀자 프론트엔드 개발 부트캠프_클론과제 후기 (카테고리 필터링 구현 map, filter, some) (0) | 2023.08.01 |
배열&객체 연습문제 1 (0) | 2023.07.19 |
up down 게임 만들기 (0) | 2023.07.19 |
가위 바위 보 게임 만들기 (0) | 2023.07.19 |