Tech is created to fix problem

배열&객체 연습문제 2 본문

연습 또 연습/js 연습문제

배열&객체 연습문제 2

furaha 2023. 7. 20. 12:22
반응형

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);
        }
}

 

아직은 구조분해랑 전개연산자를 사용하는게 익숙하지가 않다,,!

무한 메소드 체이닝을 피하려면 구조분해 사용이 익숙해져야하고

코드를 간략화하기 위해서는 전개연산자를 적절히 사용해주어야한다!

반응형