JavaScript

[모던 JavaScript] 5.9~ 5.10 과제 정리!

보라해바라기 2022. 12. 9. 22:07
SMALL
  • 5.9 Object.keys, values, entries
  • 5.10 구조분해할당

5.9 (1) 프로퍼티 값 더하기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프로퍼티 값 더하기</title>
</head>
<body>
    <script>
    let salaries = {
    "John": 100,
    "Pete": 300,
    "Mary": 250
    };

    function sumSalaries(obj) {
        let sum = 0;
        for (let num of Object.values(obj)) {
            sum += num;
        }
        return sum;
    }

    alert( sumSalaries(salaries) ); // 650
    </script>
</body>
</html>

5.9 (2) 프로퍼티 개수 세기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프로퍼티 개수 세기</title>
</head>
<body>
    <script>
        let user = {
        name: 'John',
        age: 30
        };

        function count(obj) {
            return Object.keys(obj).length;
        }

        alert( count(user) ); // 2
    </script>
</body>
</html>

5.10 (1) 구조 분해 할당

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>구조 분해 할당</title>
</head>
<body>
    <script>
    let user = {
    name: "John",
    years: 30
    };

    let {name, years: age, isAdmin= false} = user;

    alert( name ); // John
    alert( age ); // 30
    alert( isAdmin ); // false
    </script>
</body>
</html>

5.10 (2) 최대 급여 계산하기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>최대 급여 계산하기</title>
</head>
<body>
    <script>
    let salaries = {
    "John": 100,
    "Pete": 300,
    "Mary": 250
    };

    function topSalary(salaries) {
        let max = 0;
        let maxName = null;
        
        for(const[name, salary] of Object.entries(salaries)) {
            if(max < salary) {
                max = salary;
                maxName = name;
            }
        }

        return maxName;
    }

    alert(topSalary(salaries))
    </script>
</body>
</html>

 

 

 

 

 

 

728x90