ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2023년 05월 22일 수업 내용
    국비 교육 내용 정리 2023. 5. 22. 09:00

    * 퀴즈퀴즈 플러스

    Q1)
     연필 1다스는 연필 12자루 입니다.
      학생 1인당 연필을 1자루씩 나누어 준다고 할때 
      n명의 학생 수를 입력하면, 연필의 다스 수가 구해지는 프로그램을 작성하세요 . 
      함수(학생수) -> 다스 수 
      math 객체 메소드 사용

     

    코드:  

    function solution(n) {
        let answer=Math.ceil(n/12);
        return answer;
    }

    console.log(solution(200));


    코드 설명: 

    1. 함수는 "n"이라는 매개변수를 가지고 있습니다.
    2. 함수 내에서 "answer"라는 변수를 초기화하고, "n"을 12로 나눈 후 Math.ceil 함수를 사용하여 결과를 올림한 값을 할당합니다. Math.ceil 함수는 결과를 가장 가까운 정수로 올림합니다.
    3. 예를 들어, "n"이 200인 경우, n/12의 결과는 16.6667입니다. Math.ceil 함수는 올림하므로 "answer"의 값은 17이 됩니다.
    4. 함수는 "answer"의 값을 반환합니다.
    5. 마지막으로, 함수를 solution(200)과 같이 200을 인수로 호출합니다. 결과는 console.log를 사용하여 콘솔에 출력되며, "answer"의 값이 출력됩니다.

    이 구체적인 예에서 예상되는 출력은 17입니다. 왜냐하면 200개의 항목을 12개씩 담을 수 있는 17개의 그룹으로 나눌 수 있기 때문입니다.



    Q2)  문자 찾기 
    한개의 문자열을 입력받고, 
    특정 문자를 입력받아 해당 특정문자가 입력받은 문자열에 몇 개 존재하는지 알아내는 프로그램을 작성하세요. 
    (입력) 첫 줄에 문자열이 주어지고, 
       두 번째 줄에 문자가 주어진다. 
    - COMPUTERPROGRAMMING 
      -R 

    (출력) 첫 줄에 해당 문자의 개수를 출력한다. 
    3
    let str = "COMPUTERPROGRAMMING"; 
    console.log(solution(str, 'R)) //3

     

     

    답변)

    let str = "COMPUTERPROGRAMMING";

    function solve(str, target){
     let answer = 0;
     for (let x of str){
        if (x===target) answer++;
     }

        return answer;
    }

    console.log(solve(str, 'P')); //2

     

     


    Q3) 소문자로 된 한개의 문자열이 입력되면 
      중복된 문자를 제거하고  출력하는 프로그램을 작성하세요.
    제거된 문자열의 각 문자는 원래 문자열의 순서를 유지합니다. 

    (입력) 첫 줄에 문자열이 입력됩니다. 
    ksetkkset 

      (출력) 첫 줄에 중복된 문자가 제거된 문자열을 출력합니. 
    kset

    ==========================================================================================

    const arr = [1, "2", "삼", 4.0];
    const arr2 = new Array(1, "2", "삼", 4.0 );

    const obj = {
        0: 1,
        1: "2",
        2: "삼",
        3: 4.0,
        length: 4

    };

    console.log(arr);
    console.log(arr2);
    console.log(obj);

    console.log(arr[3]);
    console.log(obj[3]);

    // symbol.Iterator: 배열의 정렬과 for-of(netx()) 반복문을 사용할수 있도록 돕는 자료형
     for (let a of arr){
        console.log(a);
     }


    //  for(let o of obj){
    //     console.log(o);
    //  }

    //Array.from: 배열과 유사한 object(객체)를 배열로 변환
    for (let o of Array.from(obj)){
        console.log(o);
    }

    console.log(arr == arr2); // false
    console.log(arr == arr); // true
    console.log(typeof arr); // object
    // 배열의 내부 반복문
    // forEach((element,index,arr)=>{})
    // map((element)) => {return element2})

    const numbers = [1,2,3,4];
    const fruits = ['apple','banana','cherry'];


    //forEach()
    fruits.forEach(function (el,idx,arr){
      console.log(el,idx,arr)  
    });

    const f = fruits.forEach(function(fruit,index){
         console.log(`${fruits}-${index}`);
    });

    console.log(f); //undefined (따로 반환되는 값이 없으므로)

    const f2 = fruits.forEach((fruit,index)=>{
        console.log(`${fruit}-${index}`);
    });



    //map()
    // callback 에서 반환된 특정한 데이터들의 새로운 배열을 반환함
    const m1 = fruits.map(function (fruit,index){
        return `${fruit}-${index}`;
    })

    console.log(m1);

    const m2 = fruits.map(function (fruit,index){
        return {
            id: index,
            name: fruit
        }
    });
    console.log(m2);

    const m3 = fruits.map((fruit,index) => ({
        id : index,
        name: fruit
    }));
    console.log(m3);

    //filter()
    const ft = numbers.filter(number => { // 조건이 true인 경우의 값들로 된 배열이 반환됨
        return number < 3;

    });
    console.log(ft);
    console.log(numbers); // filter()도 map()과 마찬가지로 원본 배열에는 영향을 주지 않음.

    const ft2 = numbers.filter(number => number<3);
    console.log(ft2);

    //find()
    const fd = fruits.find(fruit =>{
        return /^b/.test(fruit); // 대문자 B로 시작하는 item이 찾아지면 반환
    });

    console.log(fd);

    //findIndex()
    const f1 =fruits.findIndex(fruit => {
        return /^c/.test(fruit);

    });
    console.log(f1);

    //includes(): 특정 데이터가 포함돼 있는지 확인
    console.log(numbers.includes(3));
    console.log(fruits.includes('Arnie'));

     

     

    < 노드 검색>

    const myTag = document.querySelector('#content');
    console.log(myTag);

    //자식 요소 노드
    console.log(myTag.children);
    console.log(myTag.children[1]);
    console.log(myTag.firstElementChild);
    console.log(myTag.lastElementChild);


    //부모 요소 노드
    console.log(myTag.parentElement);

    //형제 요소 노드
    console.log(myTag.previousElementSibling);
    console.log(myTag.nextElementSibling);

    const myTag2 = document.querySelector('#list-1');
    console.log(myTag2.previousElementSibling);
    console.log(myTag2.nextElementSibling);
    console.log(myTag2.parentElement.nextElementSibling);
    const myTag = document.querySelector('#list-1');
    console.log(myTag);

    // innerHTML
    // 요소 안에 있는 html 자체를 문자열로 return 해줌.
    // 태그와 태그 사이의 들여쓰기와 줄바꿈 그대로
    console.log(myTag.innerHTML);
    // myTag.innerHTML = '<li>weird</li>';
    // console.log(myTag.innerHTML);
    myTag.innerHTML += '<li>weird</li>';

    // outerHTML
    // 해당 요소를 포함한 전체 HTML 코드를 문자열로 return
    console.log(myTag.outerHTML);

    // textContent
    // 요소 안에 있는 내용들 중에서 html태그를 제외한 텍스트만 가져옴

    console.log(myTag.textContent);

    myTag.textContent = 'new text!';
    myTag.textContent = '<li>weird</li>';

     

    // 기존의 요소들을 덮어쓰는 방식
    const today = document.querySelector('#today');
    console.log(today);

    console.log(today.innerHTML);
    today.innerHTML = '<li>처음</li>' + today.innerHTML;
    today.innerHTML = today.innerHTML + '<li>마지막</li>';

    today.outerHTML = '<p>이전</p>' + today.outerHTML;

    const newToday = document.querySelector('#today');
    newToday.outerHTML = newToday.outerHTML + '<p>다음</p>'

     

    //  요소 노드 추가하기
    //  요소 노드를 직접 생성해서 그 요소만 필요한 곳에 추가
    const tonday = document.querySelector('#today');

    // 3단계
    // 1.요소 노드 만들기: CreatElement('태그이름');
    const first = document.createElement('li');
    console.log(first);

    // 2. 요소 노드 꾸미기 : textcontent. innserHTML, ...
    first.textContent = '처음';
    console.log(first);

    // 3. 요소 노드 추가
    // NODE.prepend(), append(), after(), before()

    //prepend()
    tonday.prepend(first);

    //append()
    const last = document.createElement('li');
    last.textContent = '마지막';
    tonday.append(last);

    //before()
    const prev = document.createElement('p');
    prev.textContent = '이전';
    tonday.before(prev);

    //after()
    const next = document.createElement('p');
    next.textContent ='다음';
    tonday.after(next);

     

    const today = document.querySelector('#today');
    const tomorrow = document.querySelector('#tommorow');

    //노드 삭제하기 : NODE, remove()
    // tomorrow.remove();
    // today.children[2].remove();

    // 노드 이동하기: prepend,append,before,after
    tomorrow.children[1].after(today.children[1]);
    today.children[1].before(tomorrow.children[2]);
    tomorrow.lastElementChild.before(today.children[0]);


    // 2) 생성자 함수(prototype)

    function User(first, last){
        this.firstName = first;
        this.lastName = last;
    }

    // 생성자 함수가 할당된 인스턴스(객체)들
    // {} 없이(객체 리터럴 방식 대신에) 손쉽게 객체 데이터 생성

    const angel = new User('Angel','kim');
    const amy =new User('Amy','kang');
    const neo = new User('neo','park');

    console.log(angel);
    console.log(amy);
    console.log(neo);

    User.prototype.getFullName = function () {
        return `${this.firstName} ${this.lastName}`;
    }

    console.log(angel.getFullName);
    console.log(amy.getFullName);
    console.log(neo.getFullName);
    // 3) new object()로 생성하는 방식
    // 기본 객체인 object()를 기반ㅇ느로 생성하는 방식
    // 참고로만 알아 둠. ES6 이전 언어조자, 객체 리터럴 방식  권장

    const user = new Object();

    user.age = 10;
    user.name = 'jiny';

    console.log(user);
    console.log(typeof user);
    console.log(user.age);
Designed by Tistory.