본문 바로가기
Javascript

for문, while문, forEach문 적재적소로 활용하기

by Antonio Bae 2023. 7. 3.

정규표현식->많은 삽질 필요
[ns]a[^0-9]\.xls : 숫자빼고
myArray\[[0-9]\] : 역슬래시 붙혀 이스케이프
\r\n\r\n : 줄바꿈
\d : 숫자하나
\D : 숫자를 제외한 문자하나
myArray\[\d\] == myArray\[[0-9]\]
\d : 문자혹은 숫자 하나(영소,영대,숫자)
\c : Ctrl-Z
\w : 한글자
[0-9]+ : 숫자 한자리 이상 연속된 숫자
\w+@\w+\.\w+ : 일반 이메일 주소
[\w]+@[\w]+\.\w+
+ : 1 또는 여러개 == {1,}
* : 0 또는 여러개 == {0,}
? : 0 또는 1 == {0,1}
*? : 글자가 하나 이상 있으면 된다
ex) https? : s가 있던지 없던지
https:\/\/[\w.\/]+ : http,https://www.forta.com/
[\r]?\n[\r]?\n : 엔터 두번 즉, 줄바꿈 찾을때
. : 한글자
#[0-9A-Fa-f]{6} : 색상표기할때처럼 6개 문자 찾을때!
#0FOFOFF : 매칭! 한글자 넘더라도 찾아냄
\D{1,2}[-\/]\d{1,2}[-\/]\d{2,4} :01-01-01 , 54-67-9999 매칭!

\d: \$\d{3,}\.\d{2} : 1001:$496.80   --->숫자:$숫자3개.숫자2개

 

학생들의 과목별 점수를 자유자재로 불러오고 싶을때,

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=, initial-scale=1.0">
    <title>while</title>
</head>

<body>
    <script>
        const englishClass = [99,67, 80, 70, 76];
        let engTotal = 0;

        englishClass.forEach(function(v,i,a){
            engTotal += v;
        });
        document.write("<br>");
        document.write("영어점수 합:" +(engTotal).toString()+ "<br>");
        document.write("영어점수 평균:" + engTotal/englishClass.length.toString() + "<br>");
        //문자로 바꿔주는것

    </script>
</body>

</html>

 

다음으로 forEach를 활용한 반복문에 대해 자세히 설명드리겠습니다.

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=, initial-scale=1.0">
    <title>while</title>
</head>

<body>
    <script>
        const scoreClass = [
            [99, 67, 80, 70, 76],//English
            [82, 84, 79, 64, 80],//Math
            [80, 79, 99, 95, 70]//Korean
        ];
        function plusEach(jumsooList) {
            let tempSum = 0;
            let tempAvg = 0;
            jumsooList.forEach(function(v,i,a){
                tempSum +=v;
            });
            tempAvg = tempSum / jumsooList.length;
            return [tempSum,tempAvg];
        }

        function avgEach() {}

        scoreClass.forEach(function (v, i, a) {
            document.write(plusEach(v)[0]+" " +plusEach(v)[1]+"<br>");
        });

    </script>
</body>

</html>

계산기 두드려볼것!값을 변경해서 잘 작동되는지 확인해볼것!

함수호출 2번을 한번으로 수정

            scoreClass.forEach(function (v, i, a) {
                    let printValue = plusEach(v);
                    document.write(printValue[0]+" " +printValue[1]+"<br>");
        });

 

마진 개념

 

 

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=, initial-scale=1.0">
    <title>마진</title>
    <style>
        /* 315x230 마진 8 4 6 패딩 4 보더 8 9 10 13 */
        /* 일때 컨텐츠의 너비와 높이는? 높이: 230+8+6+4+8+10=266 너비: 4+4+315+9+13= 345 */
        * {
            margin: 8px 4px 6px;
            padding: 4px;
        }

        .zB {
            width: 315px;
            height: 230px;
            background-color: orange;
            color: black;
            display: flex;
            text-align: center;
            border: 8px solid pink;
            /* 너비는 130이 됨 */
            /* 높이는 80이 됨 */
           
            border-top: 8px solid red;
            border-right: 9px solid green;
            border-bottom: 10px solid yellowgreen;
            border-left: 13px solid blue;

           
        }
    </style>
</head>

<body>
    <label>
        이름
        <input type="text" name="name">
    </label>
    <label>
        나이
        <input type="number" name="ages">
    </label>
    <input type="submit" value="제출">
    <p class="zB">zard</p>

    <script>

    </script>
</body>

</html>

 

최대공약수 최소공배수

var inNum1 = parseInt(prompt("숫자 2개를 입력하세요 :1st Number"));
        var inNum2 = parseInt(prompt("숫자 2개를 입력하세요 :2nd Number"));
        var tempNum = 0;
        var gcd = 0;

        if (inNum1 >= inNum2) {
            tempNum = inNum2;
            // 작은수를 temp에 저장
        } else {
            tempNum = inNum1;
            // 아니면 큰수 저장
        }
        for (i = 1; i <= tempNum; i++) {
            if (inNum1 % i == 0 && inNum2 % i == 0) {
                // 두 수 모두 나머지가 0이면(둘다 약수이면)
                gcd = i;
                // 최대공약수 g는 i
            }
        }

        document.write("최대공약수는: " + gcd + "<br>");
        document.write("최소공배수는: " + inNum1 * inNum2 / gcd);