ゼロ秒JS-デジタル野球を実現(2)


使用4-6複文(星空作業)

	// 별찍기 1 ~ 5
        let n = 1
        while(n <= 5){
            console.log('*'.repeat(n));
            n ++
        }  
        // 별찍기 5 ~ 1
        let n = 0
        while(n <= 5){
            console.log('*'.repeat(5 - n));
            n --
        }  
        // 공백포함 별찍기
        let n = 1
        while(n <= 5){
            console.log(' '.repeat(5 - n) + '*'.repeat(n))
            n++
        }

4-7スタージョブが正しい

        // 별찍기 13531
        let n = 4
        while(n >= -4){
            console.log('*'.repeat(5 - Math.abs(n)))
            n -= 2
        }

        // 별찍기 다이아몬드
        let n = 4
        while(n >= -4){
            console.log(' '.repeat(Math.abs(n)/2) + '*'.repeat(5 - Math.abs(n)))
            n -= 2
        }

4-8重複抽出なし


配列内のさまざまな方法を理解する
1)要素を追加、削除する方法:配列の先頭または末尾にメソッドを追加または削除します.
  • arr.push(items):配列の末尾に要素
  • を追加
  • arr.pop(items):タイルの末尾要素
  • を削除
  • arr.shift(items):タイルのプリアンブル
  • を削除
  • arr.unshift(items):タイルの前に要素
  • を追加
    2)要素を自由に扱う方法

  • arr.splice():配列に要素を追加、削除、置換する方法.

  • arr.splice(indexNumber,deleteCount):arrのindexNumberからdeleteCountの数字と同じ要素を削除します.また、変数にspliceを加え、削除した値を返すことができます.

  • arr.splice(0,2,element 1,element 2):arrの0番インデックスから2つの要素を削除し、その位置をelement 1とelement 2で置き換えます.

  • arr.splice(2,0,element 1,element 2):arrの2番インデックスから0要素を削除し、element 1とelement 2を追加します.//deleteCountを0に設定すると、要素を削除せずに新しい要素を追加できます.
  • デジタル野球用
            while(n <= 3){
                const index = Math.floor(Math.random() * (10 - n))
                answer.push(numbers[index])
                numbers.splice(index,1)
                n += 1
            } 

    4-9 for文と配列の比較


    JavaScriptの代表的な重複文:for,while
  • for文は繰り返し回数を指定できるため、繰り返し回数を指定する際に主に使用され、条件は繰り返し回数を指定するため、2つの使い方はやや異なります.
  • 1)for文の使用
  • for文構成:for(開始;条件;終了){内容}==for([初期化];[条件];[final式])
  • // example 1)
    // n이 10보다 작거나 같을 때 까지 n에 1씩 더하고 콘솔에 출력한다.
    
    for(let n = 1; n <= 10; n++){
        console.log(n) // 1,2,3,4,5,6,7,8,9,10
    }
    2)while文の使用
    構成
  • while文:while(条件){コンテンツ}
  • // example 2)
    // i가 10보다 작거나 같을 때 까지 i에 1씩 더하고 콘솔에 출력한다.
    
    let i = 0
    while(i <= 10){
      console.log(i) // 0,1,2,3,4,5,6,7,8,9,10
      i++
    }
  • while文の実行中に脱出したい場合は、条件文を書いた後にbreakを加えることができます.
  • //example 3)
    // n이 10보다 작거나 같을 때 까지 n에 1씩 더한 후 콘솔에 출력한다.
    // 단, n이 5보다 같거나 크다면 **탈출한다**
    let n = 0;
    while (n <= 10) {
      if (n >= 5) {
        break;
      }
      console.log(n); // 0,1,2,3,4
      n++;
    }
  • 切断と同様にcontinueも使用されている.continueは重複文を実行しますが、continueを使用する条件文を除きます.
  • //example 3)
    // n이 10보다 작거나 같을 때 까지 n에 1씩 더한 후 콘솔에 출력한다.
    // 단, n이 5보다 같거나 크다면 **탈출한다**
    
    let n = 0;
    while (n <= 10) {
      n++;
      if (n % 2 === 0) {
        // n%2 === 0 : 2로 나눈 나머지가 0인 수, 즉 2의 배수이자 짝수 인 수를 제외하고 출력한다.
        continue;
      }
      console.log(n);
    }
    3)比較アレイ
  • 配列はオブジェクトなので、配列を===と比較するとfalseが表示される可能性があります.配列の値は1つずつ比較します.
  • 4-10ストライク

  • for for for文のもう一つの使い方:forEach/for(ループ配列)/for in(ループオブジェクト)
  • forEach()文は、各アレイ要素に対して所定の関数を実行する方法であり、アレイ内の要素に対して操作を繰り返すことができる.したがって、Arrayオブジェクトでのみ使用できます.(ES 6はMapとSetをサポート)
  • 
    // example 1)
    // arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
    //currentvalue === element //index === index // array === array
    const arr = ['가', '나', '다', '라'];
    arr.forEach(function(element, index, array){
        console.log(`${array}${index}번째 요소 : ${element}`);
    });
    /*
    가,나,다,라의 0번째 요소 : 가
    가,나,다,라의 1번째 요소 : 나
    가,나,다,라의 2번째 요소 : 다
    가,나,다,라의 3번째 요소 : 라
    */
    
    // example 2)
    // 숏코드 
    // 배열의 첫번째부터 마지막까지 반복하며 출력가능
    
    array = ['엄마','아빠', '오빠']
    array.forEach(family => console.log(family))
    array.forEach(function(family){
        template = `내가 사랑하는 ${family}`
        console.log(template)
    })
  • for...文は、繰り返し可能なオブジェクト(Array、Map、Set、String、TypedArray、argumentsオブジェクトなどを含む)を繰り返し、個々の属性値ごとにループを生成し、文付きカスタム繰り返しフックを呼び出します.//forを使用するには、アセンブリオブジェクトに[Symbor.iterator]プロパティが必要です.
  • const arr = [1, 2, 3];
    for (const item of arr) {
      console.log(item); // 1, 2, 3
    }
  • for...in文は、継承された列挙可能属性、オブジェクトから文字列へのキーで指定されたすべての列挙可能属性を繰り返し実行します.(Symbolで指定した鍵の属性は無視)
  • 
    // example 1)
    // for of 와 똑같은 코드를 적용했을 때 객체에 해당하는 key값이 출력된다. 배열로 따지면 index가 출력된다.
    
    const arr = [1, 2, 3];
    for (const item in arr) {
      console.log(item); // 0, 1, 2
    }
    
    
    // example 2)
    // 객체를 탐색할 경우
    
    const obj = {
        a: 1,
        b: 2,
        c: 3
      };
      
    for (const item in obj) {
        console.log(item) // a, b, c
        console.log(obj[item]) // 1,2,3
    
        answer = obj[item]
        console.log(`${item} : ${answer}`) // a:1, b:1, c:3
    }
    
  • Object.entries():オブジェクトが持つすべてのプロパティと値のペアを配列形式で返します.
  • // example 1)
    test = {
        a: 1,
        b: 2,
        c: 3
    };
    
    console.log(Object.entries(test))
    // [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
    
    //example 2)
    const object1 = {
        a: 'somestring',
        b: 42
      };
      
    for (const [key, value] of Object.entries(object1)) {
        console.log(`${key}: ${value}`);
    }
  • Array.entries():メソッドは、キーと値を取得するために配列で使用される反復器(interator)として実行できます.
  • test = [1,2,3,4]
    
    for(const[index,element] of test.entries()){
      console.log(index,element);
    }
    /*
    0 1
    1 2
    2 3
    3 4
    */

    4-11テンプレート文字列(backtic)

  • Template literal(テンプレート文字列):引用符ではなくbacktic(`)を使用して文字列を作成し、変数を${}で囲み、+なしで文字列を使用できます.
  •         logs.appendChild(document.createTextNode(strike + 'strike' + ball + 'ball'))
            logs.appendChild(document.createTextNode(`${strike} strike ${ball} ball`))

    4-12 appendChildとQ&A

  • append/appendChild
  • .textcontent:既存のすべての文字を削除し、新しい文字/appendChildを挿入します.createTextnode:既存の文字を保持および追加
  • array() fill() map()
  • 完了したコード

    <script>
        const input = document.querySelector('#input');
        const check = document.querySelector('#check');
        const logs = document.querySelector('#logs');
    
        // map이 나오면 함수형 프로그램
        // let numbers = Array(10).fill().map(v,i => i)
        let numbers = []
        for(let n = 0; n <= 9; n++){
            numbers.push(n)
        }
        let answer = []
        let n = 0
        for(let n = 0; n <= 3; n += 1){
            const index = Math.floor(Math.random() * numbers.length)
            answer.push(numbers[index])
            numbers.splice(index,1)
        }
        console.log(answer)
        
        let count = 0;
        check.addEventListener('click', () => {
            const value = input.value
            if(value && value.length === 4){
                if(answer.join('') === value){
                    logs.append(document.createTextNode('HR'))
                    input.value = ''
                    input.focus()
                }else{
                    let strike = 0
                    let ball = 0
                    for(const [aIndex, aNumber] of answer.entries()){
                        for(const [iIndex, iString] of input.value.split('').entries()){
                            if(aNumber === Number(iString)){
                                if(aIndex === iIndex){
                                    strike += 1
                                }else{
                                    ball += 1
                                }
                            }
                        }
                    }
                    logs.append(`${input.value}: ${strike} strike ${ball} ball`, document.createElement('br'))
                    input.value = ''
                    input.focus()
                    if(count > 10){
                        logs.append(`Game Over: ${answer.join('')}`)
                        input.value = ''
                        input.focus()
                    }else{
                        count++ 
                    }
                }
            }else{
                logs.append('에러 : 4개의 숫자를 작성해주세요.', document.createElement('br'))
                input.value = ''
                input.focus()
            }
        });
    </script>
    ソース:
    1) https://www.zerocho.com/category/JavaScript/post/57341f84420974fa1f92a761
    2) https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/join