웹 기초 (7) - JS

2025. 6. 22. 15:01·웹 기초

https://opentutorials.org/course/3085/18827

자료 - 생활코딩 WEB2 JavaScript 21~27

 

 

 

 

반복문 공부하기

document.write('<li>1</li>'); 이런 형식의 코드로 1,2,3,4.... 나오게 한다면? 이런게 10억개 있다면? 반복문이 필요해짐.

 

while(true) 이렇게 되면 무한히 반복되므로 반복문이 언제 종료될지 설정하는 것이 필요함.

var i = 0;으로 변수를 생성함. 반복문이 한번 일어날때마다 i = i + 1 을 통해 1씩 증가하도록 만들기. 이제 while(i<3) 처럼 하면 됨.

<h1>Loop</h1>
<ul>
<script>
    document.write('<li>1</li>');
    var i = 0;
    while(i < 3){
      document.write('<li>2</li>');
      document.write('<li>3</li>');
      i = i + 1;
    }
    document.write('<li>4</li>');
</script>

 

 

 

 

배열과 반복문 공부하기.

배열에서 각각의 항목들을 element 라고 함.

document.write('<li>이 안에 원소들을 반복문으로 넣기</li>')

var i = 0; 으로 카운트 값도 만들어두고 4번 실행하기 위해 while(i<4) 로 반복문 시작

[i]를 통해 카운트값을 배열의 인덱스값으로 사용.

 

그런데 배열 원소가 수정될때마다 로직을 고쳐야하는 문제가 있음.

그럼 로직에서 i<4 를 할게 아니라 i <변수.length 를 사용하면 됨.

 

반복문 안에 링크도 추가해서 사용할 수 있음.

<h1>Loop & Array</h1>
    <script>
      var coworkers = ['egoing','leezche','duru','taeho'];
    </script>
    <h2>Co workers</h2>
    <ul>
      <script>
        var i = 0;
        while(i < coworkers.length){
          document.write('<li><a href="http://a.com/'+coworkers[i]+'">'+coworkers[i]+'</a></li>');
          i = i + 1;
        }
      </script>
</ul>

 

 

 

 

배열과 반복문의 활용을 공부하기.

검사 > 콘솔 들어가서 document.querySelector('a') 하면 웹페이지에 있는 모든 a태그에서 하나만 가져오게 됨.

어떻게 다 가져올 수 있을까? document.querySelectorAll('a')

var alist = document.querySelectorAll('a');

console.log(alist[0]) 이렇게 하면 첫번쨰 a태그 나옴

console.log(alist.length) 이렇게 하면 몇개의 a태그가 있는지 출력됨.

 

var alist = documnt.querySelectorAll('a');

var i = 0;

while(i < alist.length) {

console.log(alist[i]);

alist[i].style.color = 'powderblue';

i = i + 1

}

 

이런식으로 활용하면 스타일 태그의 색깔이 파우더블루로 바뀌게 할 수 있음.

즉, 야간모드일땐 파우더블루로 주간보드일땐 선명한 블루로 보이도록 활용하는 것이 가능함.

<h1><a href="index.html">WEB</a></h1>
  <input id="night_day" type="button" value="night" onclick="
    var target = document.querySelector('body');
    if(this.value === 'night'){
      target.style.backgroundColor = 'black';
      target.style.color = 'white';
      this.value = 'day';

      var alist = document.querySelectorAll('a');
      var i = 0;
      while(i < alist.length){
        alist[i].style.color = 'powderblue';
        i = i + 1;
      }
    } else {
      target.style.backgroundColor = 'white';
      target.style.color = 'black';
      this.value = 'night';

      var alist = document.querySelectorAll('a');
      var i = 0;
      while(i < alist.length){
        alist[i].style.color = 'blue';
        i = i + 1;
      }
    }
  ">
  <ol>
    <li><a href="1.html">HTML</a></li>
    <li><a href="2.html">CSS</a></li>
    <li><a href="3.html">JavaScript</a></li>
  </ol>
  <h2>JavaScript</h2>
  <p>
    JavaScript
  </p>

 

 

 

 

함수 공부하기.

중복된 것이 1억개가 넘으면 반복문으로는 힘들고 함수가 필요함.

function 함수이름(){}

 <h1>Function</h1>
    <h2>Basic</h2>
    <ul>
      <script>
        function two(){
          document.write('<li>2-1</li>');
          document.write('<li>2-2</li>');
        }
        document.write('<li>1</li>');
        two();
        document.write('<li>3</li>');
        two();
      </script>
    </ul>
    <h2>Parameter & Argument</h2>
    <h2>Return</h2>

 

 

 

 

함수 - 매개변수와 인자 공부하기

매개변수(파라미터), argument(인자)

1+1을 어떻게 함수로 만들까?

function onePlusOne(){ document.write(1+1); }

 

sum이라는 함수로 여러 입력값을 출력할 수 있도록 만들기.

function sum(left, right)

left, right가 매개변수임. 

sum(2,3)에서 2와 3이 인자임.

<h1>Function</h1>
    <h2>Basic</h2>
    <ul>
      <script>
        function two(){
          document.write('<li>2-1</li>');
          document.write('<li>2-2</li>');
        }
        document.write('<li>1</li>');
        two();
        document.write('<li>3</li>');
        two();
      </script>
    </ul>
    <h2>Parameter & Argument</h2>
    <script>
      function onePlusOne(){
        document.write(1+1+'<br>');
      }
      onePlusOne();
      function sum(left, right){
        document.write(left+right+'<br>');
      }
      sum(2,3); // 5
      sum(3,4); // 7
    </script>
    <h2>Return</h2>

 

 

 

함수 - 리턴 공부하기

sum(2,3)을 실행하면 5가 되는 표현식을 만들고 싶은거.

그러면 document.write(sum(2,3)+'<br>'); 이나 폰트크기 변경, 색깔 변경 등을 할 수 있음

return left+right; -> 이렇게 리턴시키면 됨.

<h1>Function</h1>
    <h2>Basic</h2>
    <ul>
      <script>
        function two(){
          document.write('<li>2-1</li>');
          document.write('<li>2-2</li>');
        }
        document.write('<li>1</li>');
        two();
        document.write('<li>3</li>');
        two();
      </script>
    </ul>
    <h2>Parameter & Argument</h2>
    <script>
      function onePlusOne(){
        document.write(1+1+'<br>');
      }
      onePlusOne();
      function sum(left, right){
        document.write(left+right+'<br>');
      }
      function sumColorRed(left, right){
        // 괄호를 사용해서 2와 3을 먼저 더해주기
        document.write('<div style="color:red">'+(left+right)+'</div><br>');
      }
      sum(2,3); // 5
      sumColorRed(2,3); // 5
      sum(3,4); // 7
    </script>
    <h2>Return</h2>
    <script>
      function sum2(left, right){
        return left+right;
      }
      document.write(sum2(2,3)+'<br>');
      document.write('<div style="color:red">'+sum2(2,3)+'</div>');
      document.write('<div style="font-size:3rem;">'+sum2(2,3)+'</div>');
    </script>

 

 

 

 

 

'웹 기초' 카테고리의 다른 글
  • 사진 포폴 사이트 제작 (2)
  • 사진 포폴 사이트 제작 (1)
  • 웹 기초 (6) - JS
  • 웹 기초 (5) - JS
seo_young
seo_young
  • seo_young
    86400개의 발자국
    seo_young
  • 전체
    오늘
    어제
    • 분류 전체보기 (53) N
      • 리눅스 (11)
      • 웹 기초 (9)
      • 회로이론1 (1)
      • 자료구조 (15)
      • 백준 - C (7) N
      • 백준 - 파이썬 (7)
      • 크롤링 스터디 (0)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
seo_young
웹 기초 (7) - JS
상단으로

티스토리툴바