[모던 JavaScript] 5.4~ 5.5 과제 정리!

SMALL
  • 5.4 배열
  • 5.5 배열과 메서드

5.4 (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 fruits = ["사과", "배", "오렌지"];

        // 배열을 '복사'한 후, push 메서드를 이용해 새로운 값을 추가합니다.
        let shoppingCart = fruits;
        shoppingCart.push("바나나");

        // fruits에 어떤 값이 들어 있을까요?
        alert( fruits.length ); // 4

        // 배열 복사 가능 -> 참조 값을 복사하는 것!
        // 따지고 보면 한 배열을 중복 참조 하는 꼴
    </script>
</body>
</html>

5.4 (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 styles = ["Jazz", "Blues"];

        styles.push("Rock-n-Roll");

        //Math.floor 추가
        styles[Math.floor((styles.length-1)/2)] = "Classics";

        styles.shift();

        styles.unshift("Rap", "Reggae");
        alert(styles);
    </script>
</body>
</html>

5.4 (3) 배열 컨텍스트에서 함수 호출하기

<!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 arr = ["a", "b"];

        arr.push(function() {
        alert( this );
        })

        arr[2](); // ** a,b,function(){...} **
        // arr[2]에 있는 함수가 객체 메서드처럼 호출
        // => arr를 참조하는 this를 받고 배열 출력
    </script>
</body>
</html>

5.4 (4) 입력한 숫자의 합 구하기

<!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>
        function sumInput() {
            let numbers = [];

            while (true) { // **
                let value = prompt("숫자 입력", 0);

                if (value === "" || value === null || !isFinite(value)) { // *
                    break;
                }

                numbers.push(+value);
            }

            let sum = 0;
            for (let number of numbers) {
                sum += number;
            }
            return sum;
        }

        alert( sumInput() )
    </script>
</body>
</html>

5.4 (5-1) 최대합 부분 배열 (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>
        // 복습 필요
        function getMaxSubSum(arr) {
            let maxSum = 0;

            for (let i=0; i<arr.length ; i++) {
                let sumFixedStart = 0;
                for (let j=i; j<arr.length ; j++) {
                    sumFixedStart += arr[j];
                    maxSum = Math.max(maxSum, sumFixedStart);
                }
            }
            return maxSum;
        }

        alert( getMaxSubSum([-1, 2, 3, -9]) ); // 5
        alert( getMaxSubSum([-1, 2, 3, -9, 11]) ); // 11
        alert( getMaxSubSum([-2, -1, 1, 2]) ); // 3
        alert( getMaxSubSum([1, 2, 3]) ); // 6
        alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
    </script>
</body>
</html>

5.4 (5-2) 최대합 부분 배열 (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>
        // 복습 필요
        function getMaxSubSum(arr) {
            let maxSum = 0;
            let partialSum = 0;

            for (let item of arr) {
                partialSum += item;
                maxSum = Math.max (maxSum, partialSum);
                if (partialSum < 0 ) partialSum = 0;
            }
            return maxSum;
        }

        alert( getMaxSubSum([-1, 2, 3, -9]) ); // 5
        alert( getMaxSubSum([-1, 2, 3, -9, 11]) ); // 11
        alert( getMaxSubSum([-2, -1, 1, 2]) ); // 3
        alert( getMaxSubSum([1, 2, 3]) ); // 6
        alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
        alert( getMaxSubSum([-1, -2, -3]) ); // 0
    </script>
</body>
</html>

5.5(1) border-left-width를 borderLeftWidth로 변경하기

<!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>border-left-width를 borderLeftWidth로 변경하기</title>
</head>
<body>
    <script>
        // split, map, join 사용
        function camelize(arr) {
            return arr.split("-")
            .map ( (word, index) => index == 0 ? word // **
                    : word[0].toUpperCase() + word.slice(1) ) // **
            .join('');
        }

        alert( camelize("background-color") );
        alert( camelize("list-style-image") ); 
        alert( camelize("-webkit-transition") ); 
    </script>
</body>
</html>

5.5(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>
        // filter 사용!
        function filterRange(arr, a, b) {
            return arr.filter( item => (a <= item && item <= b));
        }

        let arr = [5, 3, 8, 1];

        let filtered = filterRange(arr, 1, 4);

        alert( filtered ); // 3,1 (조건에 맞는 요소)

        alert( arr ); // 5,3,8,1 (기존 배열은 변경 X) 
    </script>
</body>
</html>

5.5(3) 특정 범위에 속하는 요소 찾기 (배열 변경하기)

<!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>
        // splice 사용
        function filterRangeInPlace(arr, a, b) {
            for (let i=0; i<arr.length ; i++) {
                let val = arr[i];

                if (val < a || val > b) {
                    arr.splice(i, 1);
                    i--;
                }
            }
        }

        let arr = [5, 3, 8, 1];

        filterRangeInPlace(arr, 1, 4); // 1과 4 사이에 있지 않은 요소는 모두 제거함

        alert( arr ); // [3, 1]
    </script>
</body>
</html>

5.5(4) 내림차순 정렬하기

<!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>
        // sort 사용
        let arr = [5, 2, 1, -10, 8];

        arr.sort(function(a, b) {return b-a});
        // 오름차순은 a-b, 내림차순은 b-a

        alert( arr ); // 8, 5, 2, 1, -10
    </script>
</body>
</html>

5.5(5) 배열 복사본 정리하기

<!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>
        // slice, sort 사용
        function copySorted(arr){
            return arr.slice().sort();
        }

        let arr = ["HTML", "JavaScript", "CSS"];

        let sorted = copySorted(arr);

        alert( sorted ); // CSS, HTML, JavaScript   
        alert( arr ); // HTML, JavaScript, CSS (no changes)
    </script>
</body>
</html>

5.5(6) 확장 가능한 계산기

<!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>
        // this.methods
        // calculate 메서드
        // 복습 필요
        let calc = new Calculator;

        function Calculator() {
            this.methods = {
                "-": (a, b) => a - b,
                "+": (a, b) => a + b
            };

            this.calculate = function(str) {
                let split = str.split(' '), a = +split[0], op = split[1], b = +split[2];
                if (!this.methods[op] || isNaN(a) || isNaN(b)) {
                    return NaN;
                }
                return this.methods[op](a, b);
            };
            this.addMethod = function (name, func) {
                this.methods[name] = func;
            }
        };

        alert( calc.calculate("3 + 7") ); // 10

        let powerCalc = new Calculator;
        powerCalc.addMethod("*", (a, b) => a * b);
        powerCalc.addMethod("/", (a, b) => a / b);
        powerCalc.addMethod("**", (a, b) => a ** b);

        let result = powerCalc.calculate("2 ** 3");
        alert( result ); // 8
    </script>
</body>
</html>

5.5(7) 이름 매핑하기

<!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>
        // map 사용
        let john = { name: "John", age: 25 };
        let pete = { name: "Pete", age: 30 };
        let mary = { name: "Mary", age: 28 };

        let users = [ john, pete, mary ];

        let names = users.map(user => user.name);

        alert( names ); // John, Pete, Mary
    </script>
</body>
</html>

5.5(8) 객체 매핑하기

<!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 john = { name: "John", surname: "Smith", id: 1 };
        let pete = { name: "Pete", surname: "Hunt", id: 2 };
        let mary = { name: "Mary", surname: "Key", id: 3 };

        let users = [ john, pete, mary ];

        let usersMapped = users.map ( user => ({
            fullName: `${user.name} ${user.surname}`,
            id: user.id
        }));

        /*
        usersMapped = [
        { fullName: "John Smith", id: 1 },
        { fullName: "Pete Hunt", id: 2 },
        { fullName: "Mary Key", id: 3 }
        ]
        */

        alert( usersMapped[0].id ) // 1
        alert( usersMapped[0].fullName ) // John Smith
    </script>
</body>
</html>

5.5(9) 나이를 기준으로 객체 정렬하기

<!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>
        // sort 사용
        function sortByAge(users){
            users.sort( (a, b) => a.age - b.age)
        }

        let john = { name: "John", age: 25 };
        let pete = { name: "Pete", age: 30 };
        let mary = { name: "Mary", age: 28 };

        let arr = [ pete, john, mary ];

        sortByAge(arr);

        // now: [john, mary, pete]
        alert(arr[0].name); // John
        alert(arr[1].name); // Mary
        alert(arr[2].name); // Pete
    </script>
</body>
</html>

5.5(10) 배열 무작위로 섞기

<!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>
        // 복습 필요
        // 피셔-예이츠 셔플 알고리즘
        function shuffle(array){
            for (let i=array.length - 1; i>0 ; i--) {
                let j = Math.floor(Math.random() * (i+1));
                [array[i], array[j]] = [array[j], array[i]];
            }
        }

        let count = {
        '123': 0,
        '132': 0,
        '213': 0,
        '231': 0,
        '321': 0,
        '312': 0
        };

        for (let i = 0; i < 1000000; i++) {
        let array = [1, 2, 3];
        shuffle(array);
        count[array.join('')]++;
        }

        // 만들 수 있는 모든 순열의 생성 빈도를 세서 출력
        for (let key in count) {
        alert(`${key}: ${count[key]}`);
        }
    </script>
</body>
</html>

5.5(11) 평균 나이 구하기

<!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>
        // reduce 사용
        function getAverageAge(array) {
            return array.reduce( (sum, user) => sum + user.age, 0) / array.length
        }

        let john = { name: "John", age: 25 };
        let pete = { name: "Pete", age: 30 };
        let mary = { name: "Mary", age: 29 };

        let arr = [ john, pete, mary ];

        alert( getAverageAge(arr) ); // (25 + 30 + 29) / 3 = 28
    </script>
</body>
</html>

5.5(12) 중복없는 요소 찾아내기

<!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>
        // includes로 검사 후 push
        function unique(arr) {
        let result = [];
        for (let str of arr) {
            if (!result.includes(str)){
                result.push(str);
            }
          }
          return result;
        }

        let strings = ["Hare", "Krishna", "Hare", "Krishna",
        "Krishna", "Krishna", "Hare", "Hare", ":-O"];

        alert( unique(strings) ); // Hare, Krishna, :-O
    </script>
</body>
</html>

5.5(13) 배열에서 키가 있는 객체 생성

<!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>
        // reduce
        // 복습 필요
        function groupById(array) {
            return array.reduce ((obj, value) => {
                obj[value.id] = value;
                return obj;
            }, {})
        }

        let users = [
        {id: 'john', name: "John Smith", age: 20},
        {id: 'ann', name: "Ann Smith", age: 24},
        {id: 'pete', name: "Pete Peterson", age: 31},
        ];

        let usersById = groupById(users);
        alert(usersById)
    </script>
</body>
</html>

 

 

728x90

댓글