삼항연산자, 반복문, 함수, 객체,

keep_going·2023년 1월 12일
0

js

목록 보기
6/9

// 파일명: add_if.html

조건부연산자(삼항연산자)

  • 조건식? 참결과:거짓결과
let age = 13;
let age_p=(age>=18)?true:false;
document.write(age_p);
(age>=18)?document.write('성인'):document.write('청소년');
  • 조건1?값1:조건2?값2:값3;
let gr=90;
gr>=90?document.write('A'):gr>=80?document.write('B'):document.write('C');
  • 입력받은 수의 홀짝 구분하기
let inputNum = Number(prompt('숫자입력',''));
inputNum%2===0?document.write('짝수'):document.write('홀수');

// 파일명 : add_for.html

for in, for of

let brand = ['삼성', '애플', '엘지', '클라쎄', '위니아'];
        for(i in brand) {
            document.write(i);
            // => 인덱스 활용시 사용
            // => 숫자형식으로 활용
        }
        
        for(i of brand) {
            document.write(i);
            // => 배열의 요소를 각자 출력 활용
        }
  • for in 인덱스 값 출력시 3 인덱스를 '삼'으로 바꿔서 출력
for(i in brand){
  	// 놀랍게 인덱스는 숫자가 아니고 문자였군...
  	if(i === '3') {
    	i = '삼';
  	}
  	document.write(i);
}
  • for of 각 요소 출력시 엘지 요소 출력시 '이' 출력
for(i of brand) {
  	if(i === '엘지') {
    	i = '이';
  	}
  	document.write(i);
}

// 파일명: while.html

while

구간이 정해져 있지 않은 반복문

변수 정의 : 반복 시작 표현
while(조건) {
     조건이 참이면 실행되는 실행문
     조건이 거짓이 되면 반복이 끝

     조건문 사용으로 while의 참을 거짓으로 변경 반복을 끝낼 수 있음
     반복하기 증감식 구조 작성
}
  • 무한반복
while(true) {
    document.write('빵');
}
  • 일반적 사용
let a = 1;
while(a <= 10) {
    document.write(a);
    a++;
}
  • 1부터 숫자를 하나씩 증가시키면서 더하는 경우 몇을 더할떄 100을 넘는지 구해보세요
let i = 1;
let sum = 0;
while(sum < 100) {
    sum += i;
    i++;
}
document.write(`${i}를 더할때 100을 넘으며 그때의 값은 ${sum}입니다.`)
  • 입력받은 지폐 금액에 따라 교환되는 500원 동전의 갯수
let inputMoney = Number(prompt('지폐 금액을 입력하세요',''));
let cnt = 0;

// 이렇게 풀면 while 쓸 필요가 없음
// cnt = Math.floor(inputMoney/500);
// document.write(`500원 동전 ${cnt}개`);
        
while (inputMoney !== 0) {
    inputMoney -= 500;
    cnt++;
}
document.write(`500원 동전 ${cnt}`);
// inputMoney -= cnt*500;라고 생각했는데 오류 나는 이유?
// cnt가 증가 함에 따라 inputMoney값이 딱 0으로 떨어지는게 아니라 음수가 되는 경우가 생기기 때문
// inputMoney 값에 cnt*500한 값을 이전 값과 중첩되어 빼기때문에 원하는 cnt값이 아님

break

반복문시 조건에 맞추어 반복을 끝내는 명령

continue

반복문시 조건에 맞추어 해당 조건시 패스

  • 질문에 무조건 네라는 답이 들어올때 까지 반복 실행, '네'가 입력되면 반복 끝
while(true) {
    let input = prompt('이벤트 참여 할래?', '');
    if (input === '네') {
        document.write('이벤트에 참여하셨습니다.')
        break;
    }
}
  • 채점 점수가 40, 50, 60, 70, -1, 80 일때 -1은 넘기고 성적처리를 계속 반복하는 반복문을 작성하시오
const grade = [40, 50, 60, 70, -1, 80];
for (i of grade) {
    if(i>0) {
        document.write(`${i}<hr />`);
    } else {
        continue;
    }
}
document.write('끝');

// 파일명: function.html

함수

정의 => 호출

  1. 익명함수
    => 변수에 저장 활용(함수명 없음)
    => 사용전 선언이 먼저
    => 무조건 선언된 함수 뒤로 호출
    let f_a=fuction(매개변수) { 반복되는 실행문 }
    let f_a = function() {
        document.write('배가 고파요~')
    }
    f_a();
  1. 선언적 함수
    => 함수명이 있는 함수
    => 함수 선언 위치는 상관없음
    => 호출 사용
    function 함수명(){ 반복되는 실행문 }
	function f_b() {
        document.write('오늘은 뭐먹지?');
    }
    f_b();

전역변수, 지역변수

let a = 10;
// => 전역변수
function f_c() {
  	let a = 20;
  	// => 지역변수
  	document.write(`${a} 나는 지역<br>`);
  	return // 함수 외부로 함수 안 결과를 주는 아이
}
f_c();
document.write(`${a} 나는 전역<br>`);

// 파일명: object.html

객체

  • 배열명[,,,]
    => 인덱스, 요소
    => 배열명[인덱스]

  • 객체명{키:값,,,}
    => 키, 값
    => 객체명['키']
    => 객체명.키

let person = {
  	name    :   'hi',
  	age     :   20
}
document.write(person['name']);

  • jquery 환경설정
    jquery.com 에서 Download the uncompressed, development jQuery 3.6.3 눌러서 컨트롤 s눌러서 작업하고 있는 폴더(d드라이브)에 저장
    // 두가지 형식 다운... 추가적으로 ui에 대한 부분도 다운
    // plugin에서 ui아니면 주소에 jqueryui로 쳐도됨
    // 최신버전으로 들어가서 제일 밑에서 다운받아서 압출 풀고 ..
    // 항상 지금 먼저 받은걸 먼저 받아야 하고 ui는 나중에 다운 받아야함.. 그 밑으로 추가로 필요한 프레임이나... 다운

// $는 선택자를 사용할때 앞에 붙이는것
// 선택자는 ()안에 넣기
// js에서 window.ready(funtion)과 같음
// 여기까지가 jquery 환경설정

두 js파일을 다른 폴더에 넣어놓고 ../로 끌어와서 쓰니까 못읽네...? 읽어오는 속도가 늦어서?
아무튼 그래서 같은 폴더내로 이동시키니 해결됨


// 파일명: jquery.html

<html lang="ko">
<head>
  	<style>
      #out_box{
          width: 800px;
          height: 800px;
          background-color: beige;
          margin: 0 auto;
      }
      /* 가로 세로 크기 값을 부모의 크기 값으로 설정 */
      #in_box{
          background-color: rgb(189, 174, 255);
      }
      
      /* addClass, removeClass 지정 스타일 */
      /* 클래스로 지정하는경우 기존 선택자가 아이디 구조일때 
      클래스명 앞에 아이디를 추가해서 우선순위를 동일시함 */
      #out_box.on{
          background-color: rgb(255, 228, 244);
      }
   	</style>
    <script src="jquery-3.6.3.js"></script>
    <script src="jquery-ui.js"></script>
    <script>
        // 이 안에서 구동되야 한다
        $(document).ready(function(){
            // 스타일 지정할때 css사용
            $('#text_1').css({
                color:'#cccccc',
                'font-size':'30px',
                backgroundColor:'aliceblue',
            });
            // 태그 스타일 지정
            $('.text').css({
                color:'white',
                'font-size':'30px',
                backgroundColor:'yellowgreen',
            });
      		// 이미지 정보 불러오기
            $('img').attr({
                src:'img/butter.jpg'
            }); 
            // 태그의 속성 변경
            let out_box_width=$('#out_box').width();
            let out_box_height=$('#out_box').height();
			document.write(out_box_width);
			
            $('#in_box').css({
                width:out_box_width/2,
                height:out_box_height/2
            });

            // 이벤트
            // $(선택자).on({
            //     이벤트명:function(){},
            //     이벤트명:function(){},
            // });
            // $(선택자).이벤트(function() {
            //     이벤트 실행
            // });

            // in_box를 클릭 out_box 색상 변경
            $('#in_box').click(function(){
                $('#out_box').css({
                    background:'azure'
                });
            });

            // in_box를 첫번째 클릭하면 out_box의 배경색이 azure로 변경이 되고 두번째 클릭 하면 bisque로 변경되게 작성
            // 첫번째 클릭 두번째 클릭을 어떻게 구분하나? 
      		// 변수를 잡아서 클릭될때마다 변수값을 증감시키면! 
      		// 아니면 변수값이 불리언값을 가지도록!
            // 슬라이드 화살표 버튼의 형식
            let clickNum = true;
            $('#in_box').click(function(){
              	// 처음 클릭할때 clickNum의 값은 true이므로
                if(clickNum === true) {
                    $('#out_box').css({
                     background:'azure'
                    });
                  	// 클릭 후 clickNum 값을 바꿔줌!
                    clickNum = false;
                } else {
                    $('#out_box').css({
                     background:'bisque'
                    });
                    clickNum = true;
                }
            });

            // - mouseenter, mouseleave
            // 애니메이터 기능
      
            // 1.addClass, removeClass
            // => css 스타일을 추가, 제거하는 부분에 시간값을 설정
            $('#in_box').click(function(){
                $('#out_box').addClass('on', 1000);
                // $(선택자).addClass(클래스명, 시간)
                // 시간은 ms기준
            });

            // 2.animate
            // => css의 position을 사용
            // => 위치값 이동 
            // => width, height 크기값
            // => margin, padding 여백값 활용
            $('#in_box').click(function() {
                $('#out_box').animate({
                    width : 400,
                    height: 200,
                    marginTop:100
                 }, 1000);
            });

            // window창에 맞춘 크기값
            let win_width=$(window).width();
            let win_height=$(window).height();
      		
      		// big_box가 실제 애니메이터로 이동되는 영역
        	// 가로크기 윈도우크기
        	// 세로크기 out_box*3크기(윈도우세로*3) 
        	// 윈도우 왼쪽 상단을 기준작업(fixed)을 해서 윈도우 크기로만 인식(스크롤이 없음)
            $('#big_box').css({
                width:win_width,
                height:win_height*3,
                position: 'fixed'
            })
      		// 윈도우의 가로세로 크기값
        	// 버튼의 위치 설정을 위해서 position값 지정
        	// 색상지정
            $('.out_box').css({
                width:win_width,
                height:win_height,
                position:'relative',
            });
            $('#out_box1').css({
                background:'red',
            });
            $('#out_box2').css({
                background:'blue'
            });
            $('#out_box3').css({
                background:'green'
            });
            $('.in_box').css({
                width:'100px',
                height:'100px',
                background:'white',
                color:'black',
                textAlign:'center',
                position:'absolute',
                bottom:'10px',
                left:'50%',
                marginLeft:'-50px',
            });
            $('#in_box1').click(function() {
                $('#big_box').animate({
                    position: 'absolute',
                  	// %로 하니까 묘하게 어긋난다
                    top: '-win_height'
                }, 1000);
            })
            $('#in_box2').click(function() {
                $('#big_box').animate({
                    position: 'absolute',
                    top: '-win_height*2'
                }, 1000);
            })
            $('#in_box3').click(function() {
                $('#big_box').animate({
                    position: 'absolute',
                    top: 0
                }, 1000);
            })
        }); // 지우면 안됨
    </script>
</head>
<body>
    <h1 id="text_1">텍스트1</h1>
    <h1 id="text_2">텍스트2</h1>
    <h1 class="text">텍스트</h1>
    <h1 class="text">텍스트</h1>
    <img src="img/butter.jpg" alt="">
    <div id="big_box">
        <div class="out_box" id="out_box1">
            <h1 class="in_box" id="in_box1"></h1>
        </div>
        <div class="out_box" id="out_box2">
            <h1 class="in_box" id="in_box2"></h1>
        </div>
        <div class="out_box" id="out_box3">
            <h1 class="in_box" id="in_box3"></h1>
        </div>
    </div>
</body>
</html>
profile
keep going

0개의 댓글