본문 바로가기

(Before)BitSchool

2014/06/12 JavaScript - 기본함수, 사용자 함수, 이벤트

반응형


indexOf 와 match


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var str="Hello World";
    document.write(str.indexOf("d")+"<br>");
    document.write(str.indexOf("WORLD")+"<br>");
    document.write(str.indexOf("world")+"<br><br>");
    
    document.write(str.match("world")+"<br>");
    document.write(str.match("World")+"<br>");
    document.write(str.match("worlld")+"<br>");
    document.write(str.match("world!"));
</script>
</body>
</html>

indexOf에 일치하는 값이 없으면 -1을 출력한다.

match에 일치하는 값이 없으면 null을 출력한다.



replace

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var str="Visit Microsoft";
    document.write(str+"<br>");
    document.write(str.replace("Microsoft", "W3Schools"));
</script>
</body>
</html>

replace는 문자 변경을 할 수 있다.



boolean 값

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var b1 = new Boolean(0);
    var b2 = new Boolean(1);
    var b3 = new Boolean("");
    var b4 = new Boolean(null);
    var b5 = new Boolean(NaN);
    var b6 = new Boolean("false");
    
    document.write("0 is boolean = "+b1+" <br>");
    document.write("1 is boolean = "+b2+"<br>");
    document.write("An empty string is boolean = "+b3+"<br>");
    document.write("null is boolean = "+b4+"<br>");
    document.write("NaN is boolean = "+b5+"<br>");
    document.write("The string 'false' is boolean = "+b6+"<br>");
    
</script>
</body>
</html>



JavaScript 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var triangle = new Object();
    triangle.sideA = 3;
    triangle.sideB = 4;
    triangle.sideC = 5;
    
    triangle.getArea = function(){
        var semiperimeter = (this.sideA + this.sideB + this.sideC)/2;
        var calculate = semiperimeter * (semiperimeter - this.sideA)*
                        (semiperimeter - this.sideB)*
                        (semiperimeter - this.sideC);
        
        return Math.sqrt(calculate);
    }
    
    alert(triangle.getArea());
    
</script>
</body>
</html>


속성을 맨처음 사용할때 만들어지고 함수도 그때 그때 만들어진다.

Math.sqrt(n)는 n의 제곱근이다.


JavaScript의 배열은 인덱스를 문자열로 할수 있어 키값 처럼 쓸 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var triangle = new Object();
    triangle['sideA'] = 3;
    triangle['sideB'] = 4;
    triangle['sideC'] = 5;
    
    triangle['getArea'] = function(){
        var semiperimeter = (this.sideA + this.sideB + this.sideC)/2;
        var calculate = semiperimeter * (semiperimeter - this.sideA)*
                                        (semiperimeter - this.sideB)*
                                        (semiperimeter - this.sideC);
        
        return Math.sqrt(calculate);
    }
    
    alert(triangle.getArea());
    
</script>
</body>
</html>

결과값은 같다.



객체 리터럴

- 자바스크립트는 문법적인 제약에 지나치게 구애받지 않고 객체를 생성 할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var triangle = {
        sideA: 3,
        sideB: 4,
        sideC: 5,
        
        getArea:function(){
        
            var semiperimeter = (this.sideA + this.sideB + this.sideC)/2;
            var calculate = semiperimeter * (semiperimeter - this.sideA)*
                                            (semiperimeter - this.sideB)*
                                            (semiperimeter - this.sideC);
            
            return Math.sqrt(calculate);
        }
    };
    
        alert(triangle.getArea());
    
    
</script>
</body>
</html>

이러한 표기법을 JavaScript Object Notation - 자바스크립트 객체 표기법 - JSON이라고 부른다.

 자바스크립트 클래스를 정의하는 세가지 방법

1. 함수사용

 가장 일반적인 방법중 하나이다. 일반적인 자바스크립트함수를 정의하고나서 new 키워드를 사용하여 객체를 생성한다. 프로퍼티와 메소드를 정의하기 위해서 this를 사용하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    function Apple(type){
        this.type = type;
        this.color = "red";
        this.getInfo = getAppleInfo;
    }
    
    function getAppleInfo(){
        return this.color+' '+this.type+' apple';
    }
    
    var apple = new Apple('macintosh');
    apple.color = "reddish";
    alert(apple.getInfo());
    
    
</script>
</body>
</html>




내부적으로 사용된 메서드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    function Apple(type){
        this.type = type;
        this.color = "red";
        this.getInfo = function(){
            return this.color+' '+this.type+' apple';
        };
    }
    
 
    var apple = new Apple('macintosh');
    apple.color = "reddish";
    alert(apple.getInfo());
    
    
</script>
</body>
</html>

전역 네임스페이스의 오염을 방지하려면 메소드를 생성자 내부에 정의해야 한다. 이렇게 하면, 문법적으로 아무런 변화 없이 프로퍼티와 메소드를 사용 할 수 있다.


프로토타입에 추가된 메소드
 - 되도록이면 프로토 타입을 이용한다. 공유해서 사용할 수 있기 때문에 메모리는 더 적게 먹는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    function Apple(type){
        this.type = type;
        this.color = "red";
        
    }
    
    Apple.prototype.getInfo = function(){
        return this.color+' '+this.type+' apple';
    }

    var apple = new Apple('macintosh');
    apple.color = "reddish";
    alert(apple.getInfo());
    
    
</script>
</body>
</html>

2. 객체 기본문법 사용

 기본문법을 사용하면 자바스크립트에서 객체나 배열을 더 간단하게 정의할 수 있다. 

빈 객체 생성방법은 var o = new Object(); 또는 var o = {}; 방법이 있고 

빈 배열은 var a = new Array(); 또는 var a = [];  이렇게 객체를 바로 생성할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var apple={
            type:"macintosh",
            color:"red",
            getInfo:function(){
                return this.color+' '+this.type+' apple';
            }
    }
    
    apple.color="reddish";
    alert(apple.getInfo());
    
    
</script>
</body>
</html>
 

 이러한 객체를 때로는 싱글톤이라고 불리우기도 한다. 자바와 같은 전통적인 언어에서는 항상 해당 클래스의 인스턴스를 하나만 가질 수 있고 더 이상의 객체를 만들 수 없다. 하지만, 자바스크립에서 객체는 이미 시작할 때 부터 싱글톤이기 때문에 이러한 개념은 의미가 없다.


3. 함수를 이용한 싱글톤

세번째 방법은 위 두가지 방법을 합친 것이다. 싱글톤 객체를 정의하기 위해 함수를 사용하는 것이다.

딱하나의 객체만 만들어진것을 싱글톤이라고 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var apple=new function(){
        this.type = "macintosh";
        this.color = "red";
        this.getInfo = function(){
            return this.color+' '+this.type+'apple';
        };
    }
    
    apple.color="reddish";
    alert(apple.getInfo());
    
    
</script>
</body>
</html>

 new function(){}은 동시에 두가지 일을 하는데, 하나는 함수를 정의하는 것이고, 다른 하나는 new를 가지고 생성하는 것이다. 이에 익숙하지 않다면, 조금 혼란스러울 수도 있다. 하지만 이것은 선택 사항일 뿐이다.





For in

javascript에는 for in이라는 문법이 있다.

java의 for each문과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var person={
            fname:"John",
            lname:"Doe",
            age:25
            };
    
    /* var person={};   {key:value,key:value...}
    person['fname'] = 'John';
    person['lname'] = 'Doe';
    person['age'] = 25;
     */
    var x;
    
    for(x in person){
 //x='fname',x='lname',x='age'                                            
        document.write(person[x]+" ");
    }
    
</script>
</body>
</html>


결과값



try catch문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var txt=" ";
    function message(){
        try{
            addlert("Welcome guest!");
        }catch(err){
            txt="There was an error on this page.\n\n";
            txt+="Error description: "+ err.message + "\n\n";
            txt+="Click OK to continue.\n\n";
            alert(txt);
        }
    }
</script>
 
<input type="button" value="View message" onClick="message()"/>
 
</body>
</html>




Confirm()을 추가한 경우

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var txt=" ";
    function message(){
        try{
            addlert("Welcome guest!");
        }catch(err){
            txt="There was an error on this page.\n\n";
            txt+="Error description: "+ err.message + "\n\n";
            txt+="Click OK to continue.\n\n";
            
            if(!confirm(txt)){
                document.location.href="http://www.w3schools.com/";
            }
        }
    }
</script>
 
<input type="button" value="View message" onClick="message()"/>
 
</body>
</html>



취소를 누르면 해당 사이트로 이동을 하게 된다.

          if(!confirm(txt)){
                document.location.href="http://www.w3schools.com/";
            }




confirm 사용예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var txt=" ";
    function message(){
        
            if(confirm("탈퇴 하시겠습니까?")){
                if(confirm("정말로 탈퇴 하시겠습니까?")){
                    alert("알겠습니다.");
                }else{
                    alert("감사합니다.");
                }
            }
    }
</script>
 
<input type="button" value="탈퇴하기" onClick="message()"/>
 
</body>
</html>





Throw

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <script type="text/javascript">
        while(x = prompt("Enter a  number between  5  and  10:", "")==""){
            alert("값을 입력해주세요.");
        }
        
        try {
            if (x > 10) {
                throw "Err1";
            } else if (x < 5) {
                throw "Err2";
            } else if (isNaN(x)) {
                throw "Err3";
            }
        } catch (err) {
            if (err == "Err1") {
                document.write("Error! The value  is too high.");
            }
            if (err == "Err2") {
                document.write("Error! The value is too low.");
            }
            if (err == "Err3") {
                document.write("Error! The value is not a number.");
            }
        }
    </script>
</body>
</html>

prompt()는 입력을 받을수 있는 창을 만들어 준다.

throw로 예외발생을 던져버린다.

isNaN(x)은 int형인지 아닌지를 판별해준다. 





배열(Array)

concat()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
        function myFunction(){
            var hege = ["Cecilie","Lone"];
            var stale = ["Emil","Tobias","Linus"];
            var kai = ["Robin"];
            var children = hege.concat(stale,kai);
            var x = document.getElementById("demo");
            x.innerHTML = children;
        }
    </script>
</body>
</html>

두배열을 하나의 배열로 합쳐준다. 



pop() 

배열안의 내용을 뒤에서 부터 하나씩 지우는 함수.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
        var fruits = ["Banana","Orange","Apple","Mango"];
        
        function myFunction(){
            fruits.pop();
            var x = document.getElementById("demo");
            x.innerHTML = fruits;
        }
    </script>
</body>
</html>






push()  

배열에서 뒤쪽에 하나씩 추가하는 함수


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
        var fruits = ["Banana","Orange","Apple","Mango"];
        
        function myFunction(){
            fruits.push("Kiwi");
            var x = document.getElementById("demo");
            x.innerHTML = fruits;
        }
    </script>
</body>
</html>




reverse()

배열의 값을 역순으로 정리한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
        var fruits = ["Banana","Orange","Apple","Mango"];
        
        function myFunction(){
            fruits.reverse();
            var x = document.getElementById("demo");
            x.innerHTML = fruits;
        }
    </script>
</body>
</html>



shift()

배열에서 맨앞에 있는 요소부터 삭제된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
        var fruits = ["Banana","Orange","Apple","Mango"];
        
        function myFunction(){
            fruits.shift();
            var x = document.getElementById("demo");
            x.innerHTML = fruits;
        }
    </script>
</body>
</html>



slice()

부분배열을 만들수 있게 인덱스를 지정해서 사용할 수 있다.

부분배열이므로 다른 변수에 넣어야 사용 가능하다.

인덱스 설정 부분은  start<= X < End 이렇게 End는 포함되지 않는다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
        var fruits = ["Banana","Orange","Apple","Mango"];
        
        function myFunction(){
            var citrus = fruits.slice(1, 2);
            var x = document.getElementById("demo");
            x.innerHTML = citrus;
        }
    </script>
</body>
</html>




sort()

a,b,c...순으로 정렬을 해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
        var fruits = ["Banana","Orange","Apple","Mango"];
        fruits.sort();
        var x = document.getElementById("demo");
        x.innerHTML = fruits;
        
        /* function myFunction(){
            var citrus = fruits.slice(1, 2);
            var x = document.getElementById("demo");
            x.innerHTML = citrus;
        } */
    </script>
</body>
</html>



숫자 오름차순

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
 
        function myFunction(){
            var points=[40,100,1,5,25,10];
            points.sort(sortfunc);
            var x = document.getElementById("demo");
            x.innerHTML=points;
        } 
        
        function sortfunc(a,b){
            return a-b;
        }
    </script>
</body>
</html>



a-b<0으로써 a,b에 각각 숫자를 넣어서 비교를 해서 자리 이동을 해준다.

버블정렬이라고 할 수 있다.


숫자 내림차순

내림차순은 b-a를 해주면 역순으로 정렬된다.

b-a<0 이라는 조건이 전제하에 실행된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
 
        function myFunction(){
            var points=[40,100,1,5,25,10];
            points.sort(sortfunc);
            var x = document.getElementById("demo");
            x.innerHTML=points;
        } 
        
        function sortfunc(a,b){
            return b-a;
        }
    </script>
</body>
</html>



splice()

splice(2,2)는 인덱스2부터 2개의 인자를 제거하겠다 라는 뜻이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
 
        function myFunction(){
            var fruits=["Banana","Orange","Apple","Mango"];
            //fruits.splice(2,0,"Lemon","Kiwi");
            fruits.splice(2,2,"Lemon","Kiwi");
            var x = document.getElementById("demo");
            x.innerHTML = fruits;
        }
    </script>
</body>
</html>




unshift()

배열의 앞쪽에 삽입을 한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    
    <script type="text/javascript">
 
        function myFunction(){
            var fruits=["Banana","Orange","Apple","Mango"];
            fruits.unshift("Lemon","Pineapple");
            var x = document.getElementById("demo");
            x.innerHTML = fruits;
        }
    </script>
</body>
</html>




eval()

evaluate 평가하다 라는 함수이다.

많이 사용되는 함수이며, 작성되지않은 함수여도 사용이 가능하다.  편리한듯 하지만 보안상에 문제가 있을 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <p id="demo"> Click the button to join three arrays.</p>
    <button onClick="myFunction()">Try it</button>
    <br>
    <script type="text/javascript">
        
        eval("x=10;y=20;document.write(x*y)");
        document.write("<br>"+eval("2+2"));
        document.write("<br>"+eval(x+17));
    </script>
</body>
</html>






이벤트

두가지 이벤트 방식

1. 캡쳐링 방식 - 바깥쪽 엘리먼트부터 안쪽으로 들어가면서 이벤트를 찾아내서 호출해준다.

2. 버블링 방식 - 안쪽 엘리먼트부터 바깥쪽으로 나가면서 이벤트를 찾아내서 호출한다.


캡쳐링, 버블링 방식 선택이 표준방식이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <a id="link" href="http://www.opera.com/">say hello</a>
    
    <script type="text/javascript">
        var linkElement = document.getElementById("link");
    // linkElement.onclick = handleEvent; 기존의 방식
        linkElement.addEventListener('click',handleEvent,false); 
// true면 캡쳐링, false면 버블링
        
        function handleEvent(){
            alert("Hello");
        }
    </script>
</body>
</html>




반응형