[JS] 함수

2022. 4. 26. 11:11·Stack/JavaScript

함수???

프로그램을 작성할 때 반복적으로 하는 일을 함수로 만듦

서브프로그램이라고도 함

프로그램 안에서 각각의 작은 기능을 수행

input을 받아서 잘 처리한다음 output(return)을 해줌

 

- 함수 생성하기

함수선언문

구문

function add(a, b) {

          return a + b;

}

function: 함수선언(이건 함수야!)

add: 함수식별자 (함수이름)

a, b: 매개변수

return a + b: 반환값

add(3, 4): 함수호출 => 7

add(7,9) => 16

 

function 빵만들기(재로1, 재료2){

     재료1과 2를 섞어서 빵을 만들어

     return 빵;

}

빵만들기(밀가루, 초코);

 

function print() {

     document.write('안녕하세요여러분화요일입니다.');

}

let result2 = print();

 

함수표현식

let myFunction = function() {

     alert('abc');

}

myFunction();

 

화살표 함수

let myFunction = () => alert('abc')

 

function printMsg(from, message = '안녕'){

     console.log('메세지를 보낸 사람은 '+from+'이고 내용은 '+message+'입니다.');

}

printMsg('영희', '여러분')

 

* 호이스팅, 스코프, 매개변수, 변수, 함수, 지역변수, 전역변수, 함수선언문, 함수표현식, 리턴, undefined, NaN, Number('10'), typeof x

 

innerHTML

선택한 요소의 내용을 반환하거나 변경

src

선택한 요소의 src 속성값을 반환

1. style.속성명 (인라인 스타일로 작성된 값만 반환)

2. window.getComputedStyle(선택한 요소).getPropertyValue('스타일속성명')

(내부 스타일 속성값을 반환)

 

자바스크립트를 이용해서 css스타일을 변경하기

object.style.color='red';

 

<div class="on"></div>

자바스크립트에서 요소의 클래스를 붙이기 / 삭제하기

object.classList.add('클래스명')

object.classList.remove('클래스명')

 

자바스크를 이용해서 css스타일을 변경하기

object.style.color = 'red';

 

<div class="on"></div>

자바스크립트에서 요소의 클래스를 붙이기 / 삭제하기

object.classList.add('클래스명')

object.classList.remove('클래스명')

object.classList.toggle('클래스명')

 


 

09function.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // function consolePrint(name) {
        //     console.log(name);
        // }

        // 함수 선언문 방식
        // function 함수명(매개변수1, 매개변수2) {
        //      return 반환값;   
        // }
        // 함수 선문은 호이스팅됨
        // 함수 정의하기 전에 호출이 가능함
        // 

        "use strict"
        document.write(add(7, 9)+'<br>');
        document.write(add(578, 54789));
        console.log(namename);
        function add(a, b) {
            return a + b;
        }
        function consolePrint() {
            console.log('함수를 실행했어요');
        }

        var namename ='aaaaa';
        let result=consolePrint();
        console.log(result);

        // 기본 매개변수값 (added in ES6)
        // 전달하지 않은 매개변수의 디폴트값을 설정할 수 있음
        function showMessage(message, from='그린') {
            console.log(`메세지는 ${message}이고 보낸사람은 ${from}이다.`)
        }
        showMessage('안녕하세요', '404호')

        // 스코프: 변수의 유효범위
        // 블럭 안에서 선언하면 로컬변수(지역변수) 블럭 밖에서 선언하면 글로벌변수(전역변수)
        // var 스코프는 함수 스코프
        // let 스코프는 블럭 스코프
        // var, let, const 구분
        // 1. var 재선언가능, 호이스팅 됨(변수 선언부), 재할당 가능, 함수스코프
        // 2. let 선언가능, 블럭스코프, 호이스팅 되지 않음, 재할당가능
        // 3. const 선언과 동시에 할당, 재할당 안됨, 호이스팅 되지 않음, 블럭스코프
        let userName = 'bella';
        function print() {
            let userAge = 30;
            var variable3 = 'aaaa';
            console.log(userName);
            console.log(userAge);
        }
        {
            var variable1 = 'abc';
            let variable2 = 'deg';
        }
        console.log(variable1);
        // console.log(variable2);
        print();

        // 리턴값
        // 리턴이 없는 경우 return undefined가 생략된 것임

        // 함수표현식
        // 자바스크립트에서는 함수도 객체로 취급함
        let sayHi = function(a,b){
            alert('Hello'+ a + b + '도 안녕~~!!');
        }
        sayHi('영희','철수');
        
        // 화살표함수 (Arrow function)
        // 이름 없는 함수를 간단하게
        let sayHi2 = () => alert('Hello'); // 한 줄일 때 중괄호 생략 가능
        sayHi2();
    </script>
</body>
</html>

 

10style.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div { width: 1000px; height: 500px; background: yellow; }
    </style>
</head>
<body>
    <div></div>
    <button onclick="chBackground('rgb(255,0,0)')">pink색상</button>
    <button onclick="chBackground('rgb(0,255,0)')">red색상</button>
    <button onclick="chBackground('rgb(0,0,255)')">blue색상</button>
    <button onclick="chBackground('rgb(255,0,255)')">green색상</button>
    <button onclick="bgColorView()">배경색상알기</button>
    <script>
        // 선택한 요소의 css 속성값을 반환하기
        // 1. style.속성명 (인라인 스타일로 작성된 값만 반환)
        // 2. window.getComputedStyle(선택한요소).getPropertyValue('스타일속성명')
        // div의 배경색을 pink로 변경
        function chBackground(bgcolor) {
            document.querySelector('div').style.background=bgcolor;
            document.querySelector('div').innerHTML = `${bgcolor}입니다.`;
            console.log(document.querySelector('div').style.background)
        }
        function bgColorView() {
            // alert(document.querySelector('div').style.background);
            let div = document.querySelector('div');
            let style=window.getComputedStyle(div).getPropertyValue('background-color');
            // console.log(style);
            // alert(style.getPropertyValue('background-color'));
            alert(style);
        }
    </script>
</body>
</html>

 

11classList.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        #header {
            background-color: #eee;
            height: 80px;
            overflow: hidden;
            transition: 0.5s;
        }
        #header.on {
            height: 180px;
        }
        ul {
            display: flex;
        }
        li {
            padding: 20px;
            line-height: 40px;
        }
        #submenuBg {
            height: 100px;
            background: tomato;
        }
    </style>
</head>
<body>
    <div id="header">
        <!-- ul>li{list$}*4 -->
        <ul>
            <li onmouseenter="addOn()" onmouseleave="removeOn()">list1</li>
            <li>list2</li>
            <li>list3</li>
            <li>list4</li>
        </ul>
        <div id="submenuBg"></div>
    </div>
    <script>
        // li에 마우스를 올리면 header라는 id를 가진 요소의 클래스 on을 지정
        function addOn() {
            document.querySelector('#header').classList.add('on');
        }
        function removeOn() {
            document.querySelector('#header').classList.remove('on');
        }
    </script>
</body>
</html>

 

12classListtoggle.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 100%;
            height: 300px;
            background: pink;
        }
        div.on {
            background: yellow;
        }
    </style>
</head>
<body>
    <button onclick="chBackground()">클릭하세요</button>
    <div></div>
    <script>
        function chBackground() {
            document.querySelector('div').classList.toggle('on');
        }
    </script>
</body>
</html>

 

ex01.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * { margin: 0; padding:0; box-sizing: border-box;}
        body {
            padding: 100px;
            position: relative;
        }
        button {
            font-size: 42px;
            border: none;
            background: none;
        }
        div {
            width: 100%;
            height: 100vh;
            position: absolute;
            background: #000;     
            left:-100%;
            top: 0;  
            transition: 0.5s;
        }
        div ul {
            color: #fff;
            padding: 350px 800px;
        }
        li { 
            list-style: none; 
            font-size: 38px;
            padding: 8px 0;
        }
        div.on {
             left:0;
        }
        div button {
            color: #fff;
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>
<body>
    <button onclick="openul()">open</button>
    <div>
        <button onclick="closeul()">X</button>
        <ul>
            <li>menu1</li>
            <li>menu2</li>
            <li>menu3</li>
            <li>menu4</li>
        </ul>
    </div>
    <script>
         function openul() {
            document.querySelector('div').classList.add('on');
        }
        function closeul() {
            document.querySelector('div').classList.remove('on');
        }
    </script>
</body>
</html>

'Stack > JavaScript' 카테고리의 다른 글

[JS] input / input_if 예제  (1) 2022.04.27
[JS] 조건문  (0) 2022.04.27
[JS] 자료형  (0) 2022.04.26
[JS] let / const / var 기초  (0) 2022.04.26
[JS] print / DomElement / click 기초  (0) 2022.04.25
'Stack/JavaScript' 카테고리의 다른 글
  • [JS] input / input_if 예제
  • [JS] 조건문
  • [JS] 자료형
  • [JS] let / const / var 기초
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[JS] 함수
상단으로

티스토리툴바