< JavaScript >

* 자바스크립트 레퍼런스

https://www.w3schools.com/jsref/default.asp

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference

https://msdn.microsoft.com/ko-kr/library/yek4tbz0(v=vs.94).aspx



//===============

* Statement (문장)

https://www.w3schools.com/js/js_statements.asp

https://www.w3schools.com/jsreF/jsref_statements.asp

debugger Stops the execution of JavaScript, and calls (if available) the debugging function

throw Throws (generates) an error

try ... catch ... finally Marks the block of statements to be executed when an error occurs in a try block, and implements error handling



* 연산자

>>   : 부호비트를 확장하면서 오른쪽으로 이동

-5 >> 1 = -3


>>>  : 부호비트 확장없이 오른쪽으로 이동

-5 >>> 1 = 2147483645




* '=='(동등) , '==='(일치) 차이

77 == '77'

// true


77 === '77'

// false (Number v. String)



//========

* in 연산자

- 객체나 배열 체크

- 결과는 true, false 

var point = {x:1, y:1};

var has_x = "x" in point; // 결과 = true



//===========

* instaneof 연산자

- 클래스 체크

var d= new Data();

d instanceof Data; // true

d instanceof Object; // true

d instanceof Number; // true




* NaN (Not a Number)

isNaN() - 숫자가 아닌지 가려냄


typeof undefined           // undefined

typeof null                // object


null === undefined         // false   <=============

null == undefined          // true 



//========================

* 형변환


- 문자열 -> 숫자

str = "12.34글자";

num2 = Number(str);//숫자이외의 문자가 들어가면 NaN

num2 = parseInt(str);

num2 = parseFloat(str);



- 숫자 -> 문자열

num = 12.34;

str2 = String(num);

str2 = num.toString(2);//2진법

str2 = num.toFixed(2);//소숫점 이하 2자리




//================================

* 수숫점 계산 문제 해결

 

- 문제 현상

var float1 = 0.1 + 0.2; //결과 = 0.30000000000000004



- 해결 방법 1

var x = (0.1 * 10 + 0.2 * 10) / 10;  



- 해결 방법 2 : math.js 이용

<script src="https://unpkg.com/mathjs@5.2.3/dist/math.min.js"></script>

var float1 = math.add( math.bignumber(0.1) , math.bignumber(0.2)); // 결과=0.3




//========================

* 함수 (function)


( )없이 사용하면 함수 정의한 내용이 인용됨


function toCelsius(fahrenheit) {

    return (5/9) * (fahrenheit-32);

}

document.getElementById("demo").innerHTML = toCelsius;  // 함수의 정의된 내용이 출력됨



* 개체 (Object)

- 개체 내에 함수 사용가능

var person = {

    firstName: "John",

    id       : 5566,

    fullName : function() {

        return this.firstName + " " + this.lastName;

    }

};


person.firstName; 

person["firstName"];



//=========================

* 이벤트

https://www.w3schools.com/jsref/dom_obj_event.asp



* OnLoad

window.onload = function () {

 alert("로딩 완료");

}


window.addEventListener('load', function(){

  alert("로딩 완료");

})


window.addEventListener('DOMContentLoaded', function () {

    alert("로딩 완료");

})




//

onabort: 이미지 로딩이 중단될 때

onblur : 태그에 포커스를 잃었을 때

onchange : 요소가 변경될 때

onclick : 마우스를 클릭했을 때

ondblclick : 마우스를 더블클릭했을 때

onerror: 이미지 로딩 오류가 일어날 때

onfocus : 태그에 포커스가 갔을 때


onkeydown : 키를 눌렀을 때

onkeypress : 키를 눌렀다가 놓았을 때

onkeyup : 키를 놓았을 때


onmousedown : 마우스 버튼을 누르고 있을 때

onmousemove : 마우스 포인트를 이동했을 때

onmouseout : 마우스 포인트가 요소의 바깥으로 이동했을 때

onmouseover : 마우스 포인트가 요소로 들어왔을 때


onresize: 윈도우 크기가 변경될 때

onmouseup : 마우스를 놓았을 때

onreset : 폼이 재설정될 때

onselect : 값이 선택되었을 때

onsubmit : 양식이 제출될 때


onload: 문서 로딩이 완료됐을 때 실행된다.

onunload: 문서나 프레임셋이 사라졌을 때 실행된다.



//===========

* URI 이스케이핑

https://opentutorials.org/course/50/187

decodeURI는 encodeURI로 이스케이핑 된 문자열을 정상적인 문자열로 되돌려주는 역활


- encodeURI 와 encodeURIComponent 의 차이

decodeURIComponent는 decode URI 가 취급하지 않는  &, ?, # 등을 디코딩


encodeURIComponent("&") returns "%26".

decodeURIComponent("%26") returns "&".

encodeURI("&") returns "&".

decodeURI("%26") returns "%26".



//========================

* 배열

var cars = ["Saab", "Volvo", "BMW"]; //GOOD

var cars = new Array("Saab", "Volvo", "BMW"); //BAD


- pop : 마지막 삭제

- push : 마지막에 추가

- shift : 맨 처음 삭제

- unshift : 맨 처음 추가


- 중간 추가

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(2, 0, "Lemon", "Kiwi"); //2번째에 추가


- 중간 삭제

fruits.splice(0, 1);    //1번째 1개 삭제



- 검색

index = cars.indexOf('Volvo');

cars.splice(index,1);//검색된 것 제거



- 정렬

- 오름차순 숫자 정렬

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b){return a - b});


- 내림차순 숫자 정렬

points.sort(function(a, b){return b - a});


//=======================

* 열거형 변수 반복자 함수(closer)

Enumerable invoke() Method

https://www.tutorialspoint.com/prototype/prototype_enum_invoke.htm


['hello', 'world', 'cool!'].invoke('toUpperCase') );

            // Returns ['HELLO', 'WORLD', 'COOL!'];


['hello', 'world', 'cool!'].invoke('substring', 0, 3));

            // Returns ['hel', 'wor', 'coo']



//=======================

* 랜덤함수

- 2수사이의 랜덤수 만들기(2수 포함)

function getRndInteger(min, max) {

    return Math.floor(Math.random() * (max - min + 1) ) + min;

}



* break

- loop 빠져나오기

- label: 도 빠져나온다


labal1:{

    text += cars[0] + "<br>"; 

    text += cars[1] + "<br>"; 

    break label1;

    text += cars[2] + "<br>"; 

    text += cars[3] + "<br>";

}



//=============

* 정규식 사용

https://www.w3schools.com/js/js_regexp.asp

https://www.w3schools.com/jsref/jsref_obj_regexp.asp


https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp

https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/%EC%A0%95%EA%B7%9C%EC%8B%9D


var str = "Visit Microsoft!";

var res = str.replace(/microsoft/i, "W3Schools");


var patt = /e/;

patt.test("The best things in life are free!"); // 'e'가 있으면 true


- exec()

/e/.exec("The best things in life are free!");//문장에서 'e' 가 있으면 'e'를 리턴, 아니면 null 리턴




//===================

* eval() 함수

- 문자열을 코드로 분석하여 실행

http://iamnotokay.tistory.com/6



* with 문

- 유효범위 체인을 임시로 변경

- 매우 깊이 중첩된 개체의 여러 속성을 참조할때 타이핑 절약


- 사용 예

with(farmes[1].document.forms[0]) {

name.value = "";

address.value = "";

}

- 하지만 사용이 권장되지 않음, ""use strict";"에서 안됨

- 최적화가 힘듬, 느림, 비직관적(with내에서 함수 정의)


- 대안 예

var form=farmes[1].document.forms[0];

form.name.value = "";

form.address.value = "";



//================

* let (ES6)

- 블록내에서 지역변수로 만듬

 var x = 10;

// Here x is 10

{

    let x = 2;

    // Here x is 2

}

// Here x is 10 



* debugger 

- 자바스크립트를 멈춤




//===============================

* Arrow Functions

- function 대체

// ES5

var x = function(x, y) {

     return x * y;

}


// ES6

const x = (x, y) => x * y;



//============================

* 애니메이션

https://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_animate_3

setInterval()//주기적으로 함수 실행

clearInterval()//setInterval 해제


function myMove() {

  var elem = document.getElementById("animate");   

  var pos = 0;

  var id = setInterval(frame, 5);//5ms마다 frame함수 호출

  function frame() {

    if (pos == 350) {

      clearInterval(id);

    } else {

      pos++; 

      elem.style.top = pos + 'px'; 

      elem.style.left = pos + 'px'; 

    }

  }

}


//============================

* 특정 위치에 출력

- DOM Node에 붙히기

https://www.w3schools.com/js/js_htmldom_nodes.asp


 <div id="div1">

<p id="p1">This is a paragraph.</p>

<p id="p2">This is another paragraph.</p>

</div>


<script>

var para = document.createElement("p");//<p>태그 생성

var node = document.createTextNode("This is new.");//내용생성

para.appendChild(node);//<p>태그에 붙히기


var element = document.getElementById("div1");

element.appendChild(para);//div1에 붙히기

</script> 



//==================================================

* 쿠키 다루기

- document.cookie 값 설정

https://www.w3schools.com/js/js_cookies.asp


<script>


//쿠키 설정

function setCookie(cname,cvalue,exdays) {

    var d = new Date();

    d.setTime(d.getTime() + (exdays*24*60*60*1000));

    var expires = "expires=" + d.toGMTString();

var coo = cname + "=" + cvalue + ";" + expires + ";path=/";

    document.cookie = coo;

}


//쿠키 보기

function getCookie(cname) {

    var name = cname + "=";

    var decodedCookie = decodeURIComponent(document.cookie);

    var ca = decodedCookie.split(';');


    for(var i = 0; i < ca.length; i++) {

        var c = ca[i];

        while (c.charAt(0) == ' ') {

            c = c.substring(1);

        }

        if (c.indexOf(name) == 0) {

var coo = c.substring(name.length, c.length);

            return coo;

        }

    }

    return "";

}


//쿠키 지우기 

//https://stackoverflow.com/questions/2144386/how-to-delete-a-cookie

function delCookie(sKey, sPath, sDomain) {

    document.cookie = encodeURIComponent(sKey) + 

            "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + 

            (sDomain ? "; domain=" + sDomain : "") + 

            (sPath ? "; path=" + sPath : "");

}


</script>


</head>

<body >


<button onclick="setCookie('name1', 'val1', 300)"> Set Cookie </button><br>

<button onclick="getCookie('name1')"> Get Cookie </button><br>

<input id="input1" name="input1" value="name1" > <button onclick="delCookie(document.getElementById('input1').value)"> Delete Cookie </button><br>



//====================================================

* AJAX

https://developer.mozilla.org/ko/docs/Web/Guide/AJAX/Getting_Started

<p id="demo">Let AJAX change this text.</p>


<button type="button" onclick="loadDoc()">Change Content</button>


<script>

function loadDoc() {

  var xhttp = new XMLHttpRequest();

  xhttp.open("GET", "BAk\\ajax_info.txt", false);

  xhttp.send();

  document.getElementById("demo").innerHTML = xhttp.responseText;

}

</script>





//========================

* call() and apply() 



* 자바스크립트 예약어

- JavaScript Reserved Words

https://www.w3schools.com/js/js_reserved.asp




await*

class*

enum* 

export*

extends*

import*

let*

super*




반응형
Posted by codens