JavaScript 개요
배경
최초의 스크립트: 1987년 애플사의 HyperCard
발전 계기: 1990년대 초에 MS사에서 VB에서 사용할 수 있는 VBC(VBApplication) 개발
등장
1994년 Netscape사에서 Dynamic Web page를 웹 브라우제에서 구현하기 위한 목적으로 LiveScript 개발되었다.
1995년 Netscape는 Sun Microsystems사(Oracle에 인수됨)와 전략적 제휴를 하며 JavaScript(줄여서 JS)로 이름을 바꾸고, HTML과 Java와의 Dynamic 연동을 지원하게 되었다.
1996년 Microsoft는 인터넷익스플로어(3.0)에서 동작되는 JScript 개발하였다.
1997년 Netscape에서 ECMA(European Computer Manufacturer's Assocation) 인터네셔널에 제출한 표준안이 최초 표준안으로 채택되었다(ECMA-262 Edition 1 -> ECMAScript 1).
최신 표준 버전은 2021년 발표된 ECMA 2021(또는 ES2021)이고 현재 가장 범용적인 버전은 2009년에 발표된 ECMA-5(자바스크립트 표준)이다.
특징
서버가 아닌 클라이언트에서 실행되는 인터프리터 언어(Interpreter Language)이다.
객체 기반 언어(Object based Language)이다.
- Broswer Object: Window, Screen, Location, History, Navigator, Alert 등
- Document Object: Nodes, Elements, Attributes, text, css, event
프로토타입 기반 언어이다.
- 프로토타입 객체를 연결하여 참조하는 방법을 prototype chain이라고 부른다.
HTML 문서에 혼합하여 사용한다.
변수의 자료형을 지정할 필요가 없다. 이러한 특성을 Dynamic Typing & Dynamic Binding이라 한다.
함수형 프로그래밍, 구조적 프로그래밍을 지원한다(즉, 기술된 순서대로 실행).
클래스는 ECMAScript 6(ES6) 이상부터 지원한다(객체 기반 언어에서 객체 지향 언어로 발전하게 된 계기).
JavaScript 사용 용도
HTML Form의 입력 값을 가공하거나 검사하여 서버 쪽에 보낼 때 사용한다.
사용자의 입력을 제어하고 싶을 때 사용한다.
웹 브라우저 내의 여러 기능을 조절하고 싶을 때 사용한다.
사용자에게 메시지를 보내고 싶을 때(경고나 확인) 사용한다.
쿠키(Cookie)를 이용한 페이지 간의 Data 유지할 때 사용한다.
동적인 웹 사이트 제작(HTML 요소나 스타일 동적 변경)할 때 사용한다.
게임이나 애니메이션(HTML5 API와 연계)할 때 사용한다.
페이지 갱신 없이 서버로부터 값을 가져올 때(AJAX) 사용한다.
JavaScript 사용 위치
1. 외부형
외부 별도의 JavaScript 파일을 불러와 사용하는 방법이다.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="myscript.js"></script>
</head>
2. 내부형
HTML 문서 내에 <head> 태그 또는 <body> 태그 내에 <script> 태그를 정의하여 사용한다.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
document.write("head 내부형 자바스크립트<br>");
</script>
</head>
<body>
<script>
document.write("body 내부형 자바스크립트<br>");
</script>
</body>
▶ document는 DOM 객체를 말한다. 즉, web broswer의 body 부분을 가리킨다.
3. 인라인(In-line)형
요소 내부에서 자바스크립트 코드를 정의할 수 있다.
<p onclick="alert('인라인형 스크립트')"></p>
주석
1. Single Line Comments
// Single line 주석입니다.
▶ //는 이 뒤에 나오는 한 줄은 주석처리 된다.
2. Multi-line Comments
/*
Multi-line 주석입니다.
*/
▶ /*는 */가 나올 때까지만 주석이다.
변수
변수란?
데이터를 저장하는 기억장소를 말한다.
명시적 또는 묵시적으로 선언이 가능하다.
- ES5(1995~2015): var, [nothing]
- ES6(2015~) 추가: let, const
변수명 생성 규칙
- 영문자, 숫자, _, $ 를 포함할 수 있다.
- 영문자, _, $ 이외의 문자(특수문자 포함)나 숫자로 시작할 수 없다(즉, 맨 처음에 오는 특수문자는 _와 $만 허용한다).
- 대소문자를 구분한다.
- 예약어(Keywords), 함수명, 객체명은 변수명으로 사용할 수 없다.
: var, for, int, if, while, do, function, catch, new, this, const, true, false, NaN 등
※ Example
1) $num → (O)
2) this → (X, 예약어는 변수명으로 사용할 수 없음)
3) !sou → (X, 맨 처음에 오는 특수문자는 _와 $만 허용됨)
4) 7abc → (X, 숫자로 시작할 수 없음)
명시적 선언(var)
선언한 변수에 값을 할당할 경우(구형 웹 브라우저도 지원)를 말한다.
재선언이 가능하며, 초기값이 할당되지 않을 경우 "undefined" 자료형이 된다.
함수 내부에서 선언시 지역변수로 취급한다.
var는 기본적으로 전역변수이다.
※ 예외(다른 프로그래밍 언어의 문법과는 동작이 달라서 주의해야한다.)
▶ var: Block에서 선언시 전역변수
▶ var: 함수 내부에서 선언시 지역변수
※ Syntax
/* 참고: 본 글의 향후 JavaScript 예제에서 명령어 뒤에 세미콜론(;)을 붙이는데 이는 생략해도 에러가 발생하지 않는다.
세미콜론은 개발자의 취향이라 붙이지 않아도 된다.
*/
var a; // undefined
var b, c; // undefined, undefined
var d=1; // number
var e=d+2; // number
var x=5;
var y=6;
var z=x+y;
var z; // JavaScript에서는 재선언해도 컴파일 에러가 발생하지 않음을 주의!
var test=10; // number
test="hello"; // string
test="hello"+12; // string. "hello"는 string, 12는 number인데 자료형이 더 큰 쪽으로 형변환이 되어서 "hello12"가 된다.
묵시적 선언
예약어 없이 변수명만 선언한 것을 말한다.
재선언이 가능하며, 초기값이 할당되지 않을 경우 "undefined" 자료형이 된다.
묵시적으로 선언된 변수는 전역변수로 취급된다(즉, 함수 내부든, 외부든 묵시적으로 선언시 전역변수로 취급됨).
단,
▶ 함수 내부에서 묵시적으로 선언된 변수이고 그 함수가 호출되지 않으면 → 지역변수
▶ 함수 내부에서 묵시적으로 선언된 변수이고 그 함수가 호출되면 → 전역변수
※ Syntax
a=1;
b=a+2;
carName="Volvo";
price=200;
let 선언
재선언 불가능하며, 초기값이 할당되지 않을 경우 "undefined" 자료형이 된다.
블록 영역(Block Scope, 지역변수) 특성을 가진다.
▶ let 특성: 지역변수 & 재선언 (X)
※ Syntax
let x="John Doe";
let x=0; // let은 재선언이 불가능하다. 따라서, 컴파일 에러가 발생한다.
var y="John Doe";
var y=0; // var는 재선언이 가능하다.
※ Example
{
let x=2; // let은 블록 영역 특성을 가짐(따라서, 지역변수 취급).
var y=3; // var는 블록 내부에 정의되어도 전역변수로 취급된다.
}
...
/* 참고: console.log()는 JavaScript에서 표준 출력 함수이다. */
console.log(x); // 따라서, x는 undefined 이므로 컴파일 에러 발생한다.
console.log(y); // 한편 y는 전역변수이므로 정상적으로 출력된다.
const 선언
변수 선언할 때 값을 할당해야한다.
할당된 값을 변경하거나 재선언할 수 없으며 블록 영역을 가진다.
※ Example
const PI=3.141592;
PI=3.14; // 컴파일 에러
PI=PI+10; // 컴파일 에러
자료형(Data types)
자료형 | Description | 사용 예 |
수치형 (number) |
10진, 16진, 8진수의 형태로 표현 가능한 소수점이 없는 정수값(범위는 시스템에 따라 다름) | 0, 10, 914, -255, 04(8진수), 0xA(16진수) |
소수점이나 지수형으로 표현되는 실수 값 | var x=34.00; var y=123e5; var z=123e-5; |
|
논리형 (boolean) |
ture 또는 false | var x=false; var x=Boolean(1); ▶ 0 이외의 값은 true로 판단 |
문자열 (string) |
quotation mark("" 또는 '') 사이의 문자들의 집합. character형이 없다. |
"12345", 'Korea', 'a' |
undefined | 변수 선언 후, 값이 할당된 적이 없는 변수. 또는 type이 지정되지 않은 변수 |
var x; var y=undefined; |
null | 아무 값도 없거나 변수가 선언된 적이 없다는 의미 (예외 처리 목적으로 사용되기도 함) 일부에서는 typeof null을 object로 출력함(JS버그) |
var person = null; |
NaN | 숫자 또는 숫자형 문자가 아닌 데이터(Not a Number) | isNaN('0') // false isNaN(1) // false isNaN(1/'a') // true |
※ 연산자 == vs. === 차이
1) == 는 피연산자 간에 형 변환이 필요한 경우, 형 변환 후에 값을 비교한다.
2) === 는 피연산자 간에 형 변환 없이 값을 비교한다.
3) 따라서, == 는 type 고려 (X) & 값 비교하고, === 는 type 고려 (O) & 값 비교한다.
var a = "10"; // number인 10을 string으로 형 변환 후에 값을 비교한다. console.log(a == 10) // true // 두 피연산자의 type이 각각 string, number이므로 false를 반환한다. console.log(a === 10) // false
※ Examples (간단한 예제는 스스로 작성해보면서 연습해보도록 하자)
var a = 10;
console.log('nStr+10+1=', a + 10 + 1); // nStr+10+1=21
// + 연산자에 의해 number인 a는 string으로 형 변환이 이루어진 뒤, 문자열 덧셈이
// 진행된다.
console.log('nStr+10+1=' + a + 10 + 1); // nStr+10+1=10101;
var b = '10';
console.log('nStr+10+1=', b + 10 + 1); // nStr+10+1=10101;
x = 5;
// 10진수 5는 2진수로 101 인데, 오른쪽으로 1 bit shift 발생하면,
// 2진수 010이 된다. 출력은 10진수인 2가 출력된다.
console.log('x>>=1 : ', x >>= 1); // x>>=1 : 2
연산자 (Operators)
연산자와 우선순위
※ 가정: x = 5
연산자 | Description | 예시 | 결과 |
( ) . [ ] new | 객체 참조, 배열 첨자, 괄호 | document.write() | |
++ -- ! typeof | 단항 증감연산 | x++; | 6 |
* / % | 곱셉, 나눗셈, 나머지 연산 | 3 / 4 | 0.75 |
+ - | 덧셈, 뺄셈 | "John" + 3 | "John3" |
<< >> >>> | 쉬프트 연산 | 5 << 1 | 10 |
< > <= >= | 관계 연산 | 2 < "12" | true |
== != === !== | 상등 연산 | x === "5" | false |
& | ^ | 비트 논리 연산(AND, OR, XOR) | 5 ^ 1; | 4 |
&& || | 논리 연산(AND, OR) | (x < 10 && 3 > 1) | true |
? : | 조건 연산 | (x < 18) ? "y" : "n"; | "y" |
= += -= *= /= %= &= ^= |= | 대입 연산(산술, 비트논리) | y = 3; x %= y; x = x % y; |
2 |
>>= <<= | 대입 연산(쉬프트) | x >>= 1; | 2 |
▶ && 연산자는 || 연산자보다 우선순위가 높다.
※ Example
x = 5; // 2진수로 101
y = 1; // 2진수로 001
// XOR 논리는 둘 중 하나가 1이면 true(1), 그게 아니면 false(0) 이다.
// 따라서, x ^ y는 2진수로 100이므로, 출력은 10진수로 4가 된다.
console.log(x ^ y); // 4
특수문자 (Special Characters)
특수문자
"\" 또는 "\ " 문자로 특수 문자를 표시한다.
특수문자 | Description | 비고 |
\n | 다음 줄로 이동(new line) | document.write()에서는 적용 안됨 ▶ 모두 빈 공백 1개로 출력된다. |
\b | 뒤로 한 칸 이동(backspace) | |
\t | 탭(tab) | |
\r | 리턴(return) | |
\f | Form feed | |
\\ | 역 슬래시 | |
\' | 작은 따옴표 | |
\" | 큰 따옴표 |
※ Example
<!DOCTYPE html>
<head>
<title>Document</title>
<script>
var T = 100;
var T = "My Name";
alert("\"" + T + "\t 홍길동" + "\"");
document.write("\"" + T + "\t 홍길동" + "\"");
</script>
</head>
<body>
</body>
</html>
▶ alert 함수 내부에는 , 를 사용하면 안 된다. 실제로는 오류 없이 출력되지만, 원하는 출력이 되지 않는다.
Break up a Code Line
코드라인 연결하기
코드 라인상의 길이가 길어질 경우 백슬래시( \ )로 코드를 다음 줄에 이어서 작성할 수 있다.
문서 편집기의 문자셋에 따라서 \ 또는 \ 로 표현될 수 있다.
※ Examples
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
document.write("Hello \
World!")
</script>
</head>
<body>
</body>
</html>
▶ ES6버전에서는 아래 예제와 같이 백틱(backtick, `)내에서는 자동 개행된다(즉, 입력한 대로 출력).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
document.write(`Hello
World!`)
</script>
</head>
<body>
</body>
</html>
JavaScript의 기본 입출력
입/출력을 위한 기본 내장 객체와 함수
입/출력 구분 | 선언 내장 객체 | 함수 | Description |
출력 | window | alert(string); | 메시지 전달 용 경고 창을 띄운다. window 객체는 생략 가능 |
window | confirm(string); | 사용자의 확인을 받기 위한 확인 창을 띄운다. window 객체는 생략 가능 ▶ 확인 시 true를, 그 외의 입력은 false를 리턴한다. |
|
document | write(string); | 웹 브라우저에 출력한다. [주의] HTML 문서 전체가 load되고 난 뒤 호출되면, 기존의 문서 내용을 지운다. |
|
입력 | window | prompt(string, initial); | 대화 상자에서 입력 받은 내용을 리턴한다(입력 취소 시 null 리턴). string: 보여 주고 싶은 질문 메시지 initial: 초기값(문자열) ▶ 사용자에게 입력 받은 값은 모두 문자열이다. |
※ Examples
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var num = prompt("숫자를 입력하세요", 100);
alert("입력 받은 숫자는 " + num + "입니다.");
confirm("입력 받은 숫자를 \n브라우저에 출력할까요?");
document.write("입력 받은 숫자 <span style='color:red'><b>" +
num + "</br></span> 을 브라우저에 출력 했지요?");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var temp = confirm("확인 또는 취소 하세요!");
document.write(temp); // 확인: true, 취소: false를 출력하게 된다.
</script>
</head>
<body>
</body>
</html>
※ [ES6 버전] 백틱(₩) 내에서 표현식 삽입
- 백틱 내에서 표현식(Expression Interpolation)을 사용하여 변수 값 출력 가능하다.
- $ { } 안에 변수나 연산 식을 사용할 수 있다.
var name = '사과'; var price = 100; var num = 5; console.log(name + '의 구매가는 ' + (price * num) + '원 입니다.') // 위의 출력 형태를 아래와 같이 백틱을 사용해서 출력할 수 있다. console.log(`${name}의 구매가는 ${price * num}원 입니다.`)
Conditions
if (conditions) else ~
※ Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// prompt의 두 번째 인자는 초기값이다.
// 만약, "" 가 아닌 " " 라면,
// 사용자가 지우지 않는 다면 공백이 포함된 상태로 리턴해서
// 기대하는 출력값을 얻지 못 할 수 있으니 주의하자!
var num = prompt("2*3=?", "");
// prompt 함수의 리턴 값의 자료형은 string 이다.
document.write(typeof num);
// == 연산자는 형 변환이 필요하면, 형 변환 후에 값을 비교한다.
// 이 문제에서는 number인 6을 더 큰 자료형인 string으로 형 변환하여,
// string인 num과 string인 6의 값을 비교한다.
if (num == 6) {
alert("정답입니다.");
} else {
alert("오답입니다.");
}
</script>
</head>
<body>
</body>
</html>
switch (expression) case ~ default
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Conditions switch</title>
<script>
var str = "";
var num = prompt("숫자 입력", " ");
switch (num) {
case '0':
str += "Zero\n";
break;
case '1':
str += "One\n";
break;
case '2':
str += "Two\n";
break;
case '3':
str += "Three\n";
break;
default:
str = "잘못 입력";
}
alert(str);
</script>
</head>
<body>
</body>
</html>
Loop
while
※ Syntax
var 변수 = 초기값;
while (조건식) {
실행문;
}
※ Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var i = 1;
while (i <= 30) {
if (i % 2 == 0 && i % 6 == 0) {
document.write(i, "<br>");
}
i++;
}
</script>
</head>
<body>
</body>
</html>
do ~ while
※ Syntax
var 변수 = 초기값;
do {
실행문;
} while (조건식);
※ Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var num = prompt("1+2+3+4+...+N = ?", "");
sum = 0, i = 1;
do {
sum += i;
i++;
} while (i <= num);
document.write("do ... while문 사용 : " + sum);
</script>
</head>
<body>
</body>
</html>
for
※ Syntax
for (초기식; 조건식; 증감식) {
code block to be executed;
}
※ Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
document.write("<table border='1' style='border-collapse: collapse'>");
document.write("<tr><td>섭씨온도</td><td>화씨온도</td></tr>");
for (celsius = 0; celsius <= 10; ++celsius) {
document.write("<tr><td>" + celsius + "</td><td>"
+ ((celsius * 9.0 / 5) + 32) + "</td></tr>");
}
document.write("</table>");
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var num = prompt("Line Number", "");
for (a = 1; a <= num; a++) {
for (b = 1; b <= a; b++) {
document.write("*");
}
document.write("<br>");
}
</script>
</head>
<body>
</body>
</html>
▶ for 문의 초기식에서 변수 정의시 type이 없는 이유는 JavaScript의 문법적 특징 때문이다. 이 때문에 유사한 문법 형식을 사용하는 C++의 for문과 다르다는 점을 알고가자.
함수 (Function)
JavaScript Function
함수는 실행될 수 있는 코드들의 집합을 말한다.
함수를 호출하려면 반드시, 호출 전에 정의되어 있어야 한다.
함수를 사용하는 이유는 자주 사용되는 코드를 재 사용할 수 있으며, 프로그래밍 코드를 좀 더 블록화 시킬 수 있기 때문이다.
주로 이벤트 핸들러에서 호출 사용하지만, 일반 스크립트에서도 사용된다.
함수의 매개변수엔 자료형을 선언하지 않는다.
함수 내의 결과값을 반환할 수 있지만, 반환 자료형은 선언하지 않는다.
※ Syntax - 선언
function 함수명(param1, param2, ... ) {
실행문;
return 리턴값;
}
참조변수 = function() {
실행문;
}
▶ 이름 없는 빈 함수로 정의한다.
※ Syntax - 호출
함수명(param1, param2, ... )
참조변수명();
※ Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function sum(num1, num2) {
alert(num1 + num2);
}
var printStr =
function (str) {
alert(str);
}
</script>
</head>
<body>
<button onclick="sum(20, 10)">버튼 합계</button>
<div onclick="printStr('참조변수 함수 호출')">참조변수를 활용한 함수 호출</div>
</body>
</html>
※ 지역변수와 전역변수
구분 Description 지역변수 함수 내부에서 var로 선언한 변수, 변수를 선언한 함수 내부에서만 사용 가능, let으로 선언한 변수 전역변수 함수 내부에서 선언되지 않은 변수, 함수 내부에서 var로 선언하지 않은 변수. 페이지의 어디에서나 사용가능 ※ Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> var a = 2; b = 7; function add() { var a = 4; c = 6; document.write("a+b+c의 값은 : " + (a + b + c) + " 이다.", "<br>"); // (a + b + c) = 10 } add(); document.write("a+b+c의 값은 : " + (a + b + c) + " 이다.", "<br>"); // (a + b + c) = 15 alert(c); </script> </head> <body> </body> </html>
JavaScript Global Functions
Global Functions
Function | Description | 예시 |
decodeURI() | Decodes a URI | |
decodeURIComponent() | Decodes a URI component | |
encodeURI() | Encodes a URI | |
encodeURIComponent() | Encodes a URI component | |
eval(str) | Evaluates a string and executes it as if it was script code ▶ 문자열(str)로 표현된 자바스크립트 코드를 실행한다. ▶ 따라서, 해커로부터 취약하므로 절대 사용하지 말아야한다. |
eval("5+4") : 9 |
isFinite(value) | value가 유한의 유효한 숫자인지 검사 +infinity, -infinity, NaN 인 경우 false, 나머지는 true를 반환 |
isFinite(0) : true isFinite("2017/01") : false isFinite(100/0) : false |
isNaN(value) | value가 유효한 숫자인지 검사. Not-a-Number인 경우 true를 반환. 문자가 포함되거나, NaN, undefined일 경우 true 반환 ▶ 어떤 값이 NaN인지 판별한다. |
isNaN("5-3" : true isNaN("53"): false |
Number(object) | Converts an object's value to a number | Number("5") : 5 Number("5 5") : NaN |
parseFloat(str) | str 문자열을 파싱하여 실수 값 출력. (숫자문자와 ".", "e", "E" 이외의 다른 문자를 만날 때까지 숫자를 실수로 파싱함) |
parseFloat("5.12") : 5.12 |
parseInt(str, radix) | str 문자열을 파싱하여 radix 진법(2~36)에 해당하는 10진수 출력(지정한 진법에 대하여, 숫자 문자 이외의 다른 문자를 만날 때까지의 숫자를 정수로 파싱함. 예를 들어, 16진법의 경우 a~f, A~F까지의 문자를 숫자로 간주됨) | parseInt("5.12") : 5 |
String(object) | Converts an object's value to a string | String(5) : "5" |
※ Examples
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var numstr = prompt("수식을 입력하십시오");
document.write("입력한 수식 : " + numstr + "<br>");
document.write("답 : " + eval(numstr));
</script>
</head>
<body>
</body>
</html>
var str1, str2, str3;
str1 = '20kr5';
str2 = '20.45';
str3 = '10.4e2k';
result = parseInt(str1) + parseInt(str2);
console.log(result); // 40
// str2를 16진수로 왼쪽부터 읽어 들이면 20까지이고,
// 이를 10진수로 변환하면 32이다.
console.log(parseInt(str2, 16)); // 32
// str3은 왼쪽부터 읽어 들이면 10.4e까지가 실수이고,
// e는 10^1 이므로 반환값은 10.4 * 100 = 1040이다.
console.log(parseFloat(str3)); // 1040
▶ parseInt, parseFloat 은 시험에서 헷갈리게 나올 수 있어서 반드시 연습해야한다.
JavaScript Event Handling
Event
브라우저에서 방문 사용자가 취하는 모든 동작이나 브라우저의 상태를 말한다.
※ 이벤트 종류
구분 | 이벤트 | Description |
마우스 | onmouseover | 마우스가 지정한 요소에 올라갔을 때 발생 |
onmouseout | 마우스가 지정한 요소에서 벗어났을 때 발생 | |
onmousemove | 마우스가 지정한 요소 영역에서 움직였을 때 발생 | |
onclick | 마우스가 지정한 요소를 클릭했을 때 발생 | |
ondblclick | 마우스가 지정한 요소를 빠른 시간 내에 연속 2회 눌렀을 때 발생 | |
onmousedown | 마우스가 지정한 요소를 눌렀을 때 발생 (클릭을 때기 전에 발생) | |
키보드 | onkeypress | 지정한 요소에서 키보드가 눌렸을 때 발생 (onkeydown과 onkeyup을 포함) |
onkeydown | 지정한 요소에서 키보드를 눌렀을 때 발생 (키를 때기 전에 발생) | |
onkeyup | 지정한 요소에서 키보드를 떼었을 때 발생 (키를 때고 난 후에 발생) | |
기타 | onfocus | 지정한 요소에서 포커스가 갔을 때 발생 |
onblur | 지정한 요소에서 포커스가 다른 요소로 이동하여 잃었을 때 발생 | |
onchange | 지정한 요소에서 value 속성값이 바뀌고, 포커스가 이동되었을 때 | |
onload | 지정한 요소의 하위 요소를 모두 로딩했을 때 발생 | |
onunload | 문서를 닫거나 다른 문서로 이동되었을 때 발생 | |
onbeforeunload | 다른 문서로 이동되었을 때 발생(Edge, Chrome) | |
onsubmit | 폼 요소의 전송 버튼을 눌렀을 때 발생 | |
onreset | 폼 요소의 취소 버튼을 눌렀을 때 발생 |
객체 (Object)
객체
프로그래밍 대상을 속성과 동작을 묶어서 정의한 자료형을 말한다.
속성(Properties: 변수)과 메소드(Method : 함수)로 이루어져 있다.
JavaScript 객체 종류
사용자 정의 객체 (Custom Object)
사용자가 정의한 객체를 말한다.
내장 객체 (Built-in Object)
JavaScript 엔진에 내장되어 있는 객체(String, Date, Math, Array, Number 등)을 말한다.
BOM (Broswer Object Model)
브라우저를 제어할 수 있는 객체(window, screen, location, history, navigator 등)을 말한다.
DOM (Document Object Model)
Tree 구조의 HTML 요소에 접근할 수 있는 객체(document)를 말한다.
사용자 정의 객체
1. Object Literal 를 사용하여 생성
Object Literal를 사용하여 생성할 수 있다.
이때, 생성된 객체는 단일 객체이고 type이 아님을 주의해라.
※ Example
var person = {
name: '홍길동',
age: 40,
eyeColor: 'blue',
getEyeColor: function() {
return this.eyeColor;
}
};
person.age = 20;
console.log(person.name, '/', person.age); // 홍길동 / 20
console.log(person.getEyeColor()); // blue
2. new Object() 를 사용하여 생성
※ Example
var person = new Object();
person.name = '홍길동';
person.age = 40;
person.eyeColor = 'blue';
person.getEyeColor =
function() {
return this.eyeColor;
}
person.age = 20;
console.log(person.name, '/', person.age); // 홍길동 / 20
console.log(person.getEyeColor()); // blue
3. Object constructor 를 사용하여 생성
동일한 Object Type으로 여러 개의 객체 생성이 가능하다.
예약어 function으로 Type을 정의하고, new 연산자로 객체를 생성한다.
외부 함수 선언이다.
※ Example
function getEyeColor() {
return this.eyeColor;
}
function Person(name, age, eyeColor) {
this.name = name;
this.age = age;
this.eyeColor = eyeColor;
this.getEyeColor = getEyeColor; // 외부 함수 선언과 참조
}
var people1 = new Person('홍길동', 40, 'blue');
console.log(people1.name, '/', people1.age); // 홍길동 / 40
var people2 = new Person('슈퍼맨', 30, 'red');
console.log(people2.name, '/', people2.age); // 슈퍼맨 / 30
console.log(people2.getEyeColor()); // red
▶ Object constructor 를 사용하여 정의할 때, 함수명 첫 글자는 대문자를 따른다.
▶ 인자로 받은 값으로 생성자를 초기화할 수 있다.
▶ 외부에 정의한 함수를 참조를 사용해 정의할 수 있다.
객체 속성
객체 속성 접근
※ Syntax
objectName.property // dot scope operator 접근법
objectName["property"] // name index 접근법
▶ name index 접근 방법 사용할 때, 배열의 index가 아니라 멤버에 접근하는 방법임을 주의하자.
※ Example
var person = {name: '홍길동', age: 40, eyeColor: 'blue'};
person.age = 20;
person['name'] = '슈퍼맨';
var vname = 'eyeColor';
person[vname] = 'red';
var people = person;
people.age = 30;
person.naionality = 'English';
person.getEyeColor = function() {
return this.eyeColor;
};
console.log(people.age); // 30
delete person.age;
console.log(people.age); // undefined
console.log(person['naionality']); // English
console.log(people.getEyeColor()); // red
delete people['getEyeColor'];
▶ people은 person을 참조하게 된다.
Object - Prototype
prototype
JavaScript의 모든 객체들에 존재한다.
이미 선언된 객체의 타입에 객체의 멤버들을 추가할 때 사용한다.
※ Examples
function Point(xpos, ypos) {
this.x = xpos;
this.y = ypos;
}
var p1 = new Point(10, 20);
p1.getDistance = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
var p2 = new Point(10, 30);
console.log(p1.getDistance()); // 22.360679774997898
console.log(p2.getDistance()); // error
function Point(xpos, ypos) {
this.x = xpos;
this.y = ypos;
}
var p1 = new Point(10, 20);
Point.prototype.getDistance = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
var p2 = new Point(10, 30);
console.log(p1.getDistance()); // 22.360679774997898
console.log(p2.getDistance()); // 31.622776601683793
for / in Loop
for / in
object의 속성변수가 없을 때까지 object의 멤버를 반복하여 탐색한다.
Array에 대해서도 사용할 수 있다.
※ Syntax
for (속성변수 in 객체) {
실행코드;
}
※ Example
var person = {
name: '홍길동',
age: 20,
eyeColor: 'blue',
getEyeColor: function() {
return this.eyeColor;
}
}
for (var vname in person) {
console.log(vname, ':', person[vname]);
/*
name : 홍길동
age : 20
eyeColor : blue
getEyeColor : [Function: getEyeColor]
*/
}
배열 (Array)
JavaScript에서의 배열
하나의 변수에 여러 값을 저장하기 위해 사용한다.
항상 index에 의해 배열의 각 요소에 접근한다(name으로 접근하는 것은 Array Object가 아닌 일반 Object임).
선언 시에 배열의 크기를 정의하지 않아도 되며, 선언 후 index의 범위를 벗어나도 접근 가능하다.
배열 선언 방법
1. Literal array
※ Syntax
var array-name = [item1, item2, ... ];
※ Example
var arr = [];
arr[0] = 'a';
2. new 연산자에 의한 Array 내장객체 생성
가독성, 실행속도 등이 더 좋은 Literal array 생성 방법을 권장한다.
※ Syntax
var variable-name = new Array(item1, item2, ... );
※ Examples
var arr = new Array();
arr[0] = 'a';
// literal array 선언
var arr = ['Bus', 512, 'Taxi']; // 자료형을 섞어 원소를 가질 수 있다.
console.log(typeof arr);
for (var i = 0; i < arr.length; i++) {
console.log(typeof arr[i], arr[i]);
}
arr[4] = 10000;
console.log(arr.length); // 5
// arr[3]에 대해서는 undefined이 된다.
for (var i = 0; i < arr.length; i++) {
console.log(typeof arr[i], arr[i]);
}
Array Property and Methods
Property / Method | Description |
length | 배열의 길이(undefined 포함) |
concat(array2, array3, ... ) | 2개 또는 그 이상의 배열 객체를 하나로 합친 배열 객체로 반환 |
join(separator) | array의 모든 요소 사이에 seperator 문자를 삽입한 결과를 string으로 반환 |
pop() | 배열에 저장된 데이터 중 마지막 인덱스에 저장된 데이터를 반환하고 삭제 |
push(item1, item2, ... ) | 배열의 마지막에 새로운 item 요소들을 추가하고, 새로운 배열 length를 반환 |
reverse() | 배열 객체의 데이터 순서를 거꾸로 한 뒤 반환 |
shift() | 배열의 데이터 중 첫 번째 인덱스에 저장된 데이터를 반환하고 삭제 |
slice(start, end) | start와 end 인덱스 사이의 배열을 반환(단, end index는 포함시키지 않음) |
sort(compareFunction) | 배열 데이터에 대하여 문자를 기준으로 오름차순 정렬한다. compareFunction에 정렬 기준을 지정할 수 있다. |
splice(index, howmany, item1, ... ) | 배열 index위치에 howmany 만큼 요소를 제거하고, item 요소들을 추가한다. |
unshift(item1, item2, ... ) | 배열의 가장 앞 위치에 item 요소들을 삽입하고, 새로운 배열의 length를 반환 |
※ Example
var fruits = new Array('apple', 'banana', 'orange');
fruits[fruits.length] = 'peer';
for (idx in fruits) {
console.log(fruits[idx]);
/*
apple
banana
orange
peer
*/
}
var cars = new Array();
cars[0] = 'truck';
cars[1] = 'bus';
cars[2] = 'taxi';
console.log(cars); // [ 'truck', 'bus', 'taxi' ]
var arr = fruits.concat(cars);
console.log(arr);
/*
[
'apple', 'banana',
'orange', 'peer',
'truck', 'bus',
'taxi'
]
*/
console.log(
arr.join(' | ')); // apple | banana | orange | peer | truck | bus | taxi
var myArray = [10, 7, 23, 99, 169, 19, 11, 1];
myArray.sort(function(a, b) {
// a-b가 음수면 b가 a보다 더 큰 관계로 swap을 안하고,
// 그 결과가 양수면 a가 b보다 더 큰 관계로 swap한다.
// 이와 같은 과정을 반복하여 정렬한다.
return a - b;
// 따라서, a-b는 오름차순 정렬,
// b-a는 내림차순 정렬이다.
})
console.log(myArray);
/*
[
1, 7, 10, 11,
19, 23, 99, 169
]
*/
Objects - 내장객체 Number
Number
new 예약어로 선언되지 않더라도 객체가 될 수 있다.
▶ 즉, 숫자 원시값에 메서드를 호출하면, 자바스크립트 엔진이 자동으로 임시 Number 객체를 만들어준다.
즉, 아래 예시를 잠시 보도록 하자.
let num = 123;
console.log(num.toFixed(2)); // "123.00"
num은 선언 시 자료형은 object가 아닌 number이다. 하지만, 다음 줄에서 toFixed(2)라는 메서드를 호출하고 있는데 이게 가능할지 의문을 품는 독자가 있을 수 있다.
자바스크립트에서는 숫자 원시값에 메서드를 호출하면, 임시적으로 암묵적 객체화(autoboxing)을 사용한다. 즉, num.toFixed(2)를 처리할 때 내부적으로 new Number(num)을 잠깐 생성하고 toFixed(2)를 호출하여 호출이 끝나면 즉시 파괴한다. 이렇듯 new를 명시적으로 사용하지 않아도, 원시값이 특정 조건에서 임시로 Number 객체처럼 동작하게 된다.
또한, new를 사용하지 않으면 원시 타입(number)이고 new를 사용하면 object 타입이 된다.
var num1 = Number(123);
var num2 = new Number(123);
var num3 = 123;
console.log(typeof num1); // number
console.log(typeof num2); // object
console.log(typeof num3); // number
Property / Method | Description |
MAX_VALUE | Returns the largest number possible in JavaScript ▶ JS에서 표현 가능한 가장 큰 수이다. 소수점이 없는 정수이며 안전한 정수는 아니다. ▶ 즉, 우주 원자의 수보다 비교가 불가능할 정도로 훨씬 크다. ▷ console.log(Number.MAX_VALUE); // 1.7976931348623157e+308 console.log(Number.isInteger(Number.MAX_VALUE)); // true console.log(Number.isSafeInteger(Number.MAX_VALUE)); // false |
MIN_VALUE | Returns the smallest number possible in JavaScript ▷ console.log(Number.MIN_VALUE); // 5e-324 ▷ 이는 양자물리 수준보다 훨씬 작은 수이다. 컴퓨터 연산에선 거의 0으로 취급한다. |
NEGATIVE_INFINITY | Represents negative infinity (returned on overflow) ▷ console.log(Number.NEGATIVE_INFINITY); // -Infinity |
POSITIVE_INFINITY | Represents infinity (returned on overflow) ▷ console.log(Number.POSITIVE_INFINITY); // Infinity |
isFinite() | Checks whether a value is a finite number |
isInteger() | Checks whether a value is an integer |
isNaN() | Checks whether a value is Number.NaN |
isSafeInteger() | Checks whether a value is a safe integer ▶ 주어진 값이 정확하게 표현 가능한 안전한 정수인지 확인 ▶ -(2^53 - 1) ~ (2^53 - 1) 범위 내의 정수이면 true를, 그렇지 않으면 false를 반환 ※ JS는 숫자를 IEEE 754 부동소수점으로 저장한다. 즉, 정수도 부동소수점으로 저장해서 실제로 범위 내에 정확하게 표현 가능 여부를 확인할 필요성이 있다. ▷ console.log(Number.isInteger(9007199254740993); // true console.log(Number.isSafeInteger(9007199254740993); // false. 범위를 벗어나서 false |
toExponential(n) | Converts a number into an exponential notation ▶ 변환된 지수 표기법에서 소수점 자릿수를 n자리까지 표시. 반올림 된다. ▶ 결괏값은 string ▷ var num = 0.000125678; console.log(num.toExponential(2)); // "1.26e-4" console.log(num.toExponential(4)); // "1.2358e-4" |
toFixed(n) | Formats a number with x numbers of digits after the decimal point. ▶ 소수점 아래 자릿수를 n자리까지 표시. 반올림 된다. ▶ 결괏값은 string ▷ var num = 3.4567; console.log(num.toFixed(2)); // "3.46" console.log(typeof num.toFixed(2)); // string |
toPrecision(n) | Formats a number to x legth ▶ 전체 유효 자릿수를 기준으로 n자리까지 표현. 반올림 된다. 또한, 큰수/작은수에 대해 지수 표기법을 사용. ▶ 결괏값은 string ▷ var num = 126.4567; console.log(num.toPrecision(2)); // "1.3e+2" console.log(num.toPrecision(4)); // "126.5" console.log(num.toPrecision(6)); // "126.457" |
toString() | Converts a number to a string |
valueOf() | Returns the primitive value of a number ▶ Number 객체를 숫자 원시값으로 반환한다(즉, 객체 내부의 실제 값을 꺼내주는 메서드). ▶ Number 객체로 산술 연산시 자동으로 valueOf()를 호출해서 명시적으로 쓸 일이 잘 없다. ▶ 하지만, 객체 비교 연산 시 사용하는 경우가 있다. ▷ var num = 123; var numObj = new Number(123); console.log(num == numObj); // true console.log(num === numObj); // false. number 형과 Object 간의 비교 연산이기 때문 console.log(num + numObj); // 246. 자동으로 numObj는 valueOf()를 호출함. |
Objects - 내장객체 Math
Math
Property / Method | Description |
E | Euler's number (2.718) |
LN10 | 자연 로그(밑수 10) (2.302) (ln(10)) |
PI | pi (3.14) |
abs(x) | x에 대한 절댓값 반환 |
acos(x), asin(x), atan(x) | x에 대한 아크 삼각함수 값 반환. 단, x는 radian이다(radian = (degree/180)*pi) |
cos(x), sin(x), tan(x) | x에 대한 삼각함수 값 반환. 단, x는 radian이다. |
exp(x) | Returns the value of E^x |
log(x) | Returns the natural logarithm (base E) of x |
ceil(x) | 무조건 올림한 정수를 반환. 소수점이 조금이라도 있으면 무조건 올림하고 소수점이 없다면 그대로 반환한다. ▷ console.log(Math.ceil(1.23)); // 2 console.log(Math.ceil(1.00)); // 1 console.log(Math.ceil(-0.10)); // -0 |
floor(x) | 무조건 버림한 정수를 반환 ▷ console.log(Math.floor(-0.10)); // -1 |
max(x, y, z, ..., n) | Returns the number with the highest value |
min(x, y, z, ..., n) | Returns the number with the lowest value |
pow(x, y) | Returns the value of x to the power of y ▷ console.log(Math.pow(2,10)); // 1024 |
random() | 0보다 크거나 같고 1보다 작은 범위의 난수를 반환 |
round(x) | x를 소수 첫째 자리에서 반올림하여 정수로 반환 ▷ console.log(Math.round(10.27)); // 10 console.log(Math.round(10.5)); // 11 |
Objects - 내장객체 Date
Date
※ Syntax
var d = new Date(); // 현재 날짜 정보를 알아냄
var d = new Date(milliseconds); // 1970년 1월 1일 이후의 millisec 설정
var d = new Date(dataString); // "월 일, 년 시:분:초" 설정
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
※ Methods
get Method | set Method | Descriptions |
getFullYear() | setFullYear(x) | 두 자리 숫자의 연도를 리턴 또는 설정 ▶ getYear()가 아닌 getFullYear() 임을 주의(getYear()는 레거시 메서드로 1900년대 기준으로 뺀 값이 반환된다. 2000년대 이후로는 헷갈릴 우려로 잘 사용되지 않는다) ▷ var date = new Date(); console.log(date.getFullYear()); // 2025 console.log(date.getYear()); // 125. 2025-1900의 계산 결과이다. |
getMonth() | setMonth(x) | 0에서 11 사이의 두 자리 숫자 월을 리턴 또는 설정(0은 1월을 의미) |
getDate() | setDate(x) | 1에서 31 사이의 날짜 리턴 또는 설정 |
getDay() | setDay(x) | 0에서 6사이의 요일 리턴 또는 설정 |
getHours() | setHours(x) | 0에서 23 사이의 숫자로 시간 리턴 또는 설정 |
getMinutes() | setMinutes(x) | 0에서 59 사이의 분 리턴 또는 설정 |
getSeconds() | setSeconds(x) | 0에서 59 사이의 초 리턴 또는 설정 |
getTime() | setTime(x) | 1970년 1월 1일 이후의 경과된 시간을 1000분의 1초 단위(milliseconds)로 출력 또는 설정. ▶ Date.now()로도 같은 결과를 얻을 수 있다. ▷ var start = new Date("2025-04-01"); var end = new Date("2025-04-14"); var diff = end.getTime() - start.getTime(); // milliseconds 단위의 차이 var days = diff / (1000*60*60*24); // milliseconds에서 일로 변환 console.log("총 " + days + "일 경과"); // 총 13일 경과 |
Objects - 내장객체 String
String
new 예약어로 선언되지 않더라도 객체가 될 수 있다.
또한, new를 사용하지 않으면 원시 타입(string)이고 new를 사용하면 object 타입이 된다.
var str1 = String(123);
var str2 = new String(123);
var str3 = "123";
console.log(typeof str1); // string
console.log(typeof str2); // object
console.log(typeof str3); // string
Property / Method | Description |
length | 문자열의 길이를 반환한다. 이때, length()가 아닌 length 임을 주의하자. |
charAt(index) | 지정한 index 위치의 문자를 반환한다. |
concat(str2, str3, ... ); | str2, str3, ... 를 순서대로 문자열을 결합하여 새로운 문자열을 반환한다. |
indexOf(value, start); | start index부터 1씩 증가하여 value 문자열이 처음 발견한 곳의 index를 반환한다. 존재하지 않으면 -1을 리턴하고 start index 생략시 0번부터 검색한다. ▷ var str = "Horlo World"; console.log(str.indexOf("or")); // 1 |
lastIndexOf(value, start); | start index부터 1씩 감소하여 value 문자열이 처음 발견한 곳의 index를 반환한다. 존재하지 않으면 -1을 리턴하고 start index 생략시 문자열의 맨 마지막부터 검색한다. ▷ var str = "Horlo World"; console.log(str.lastIndexOf("or")); // 7 |
replace(searchValue, newValue); | 첫 번째로 등장하는 searchValue만 newValue로 변환. ▷ var sentence = "I love JavaScript because JavaScript is powerful."; var result = sentence.replace("JavaScript", "Python"); console.log(result); // I love Python because JavaScript is powerful. |
search(searchValue); | 지정한 searchValue(또는 regular expression) 문자열을 찾아서, 위치 index를 반환한다. 존재하지 않으면 -1을 리턴한다. |
slice(start, end); | start번째부터 end-1번째까지 문자열을 반환한다. 이때, end 인덱스는 포함하지 않는다. ▶ substring(start, end)와 기능이 같다. 차이점은 slice는 음수의 인수도 전달할 수 있다. ▷ var str = "Hello World"; console.log(str.slice(6, 11)); // World console.log(str.slice(-5)); // World. 참고로 end-1 인덱스는 -1과 같다. |
split(separator, limit); | 지정한 separator를 기준으로 문자열을 잘라서, array로 반환. limit는 separate 할 개수를 지정함(생략시 전체 문자열) ▷ var str = "Hello World"; console.log(str.split("l")); // ['He', 'o Wor', 'd']. type는 object이다. |
substr(start, length); | start index부터 length 길이의 문자열을 반환 ▷ var str = "Hello World"; console.log(str.substr(6, 5)); // World |
substring(start, end); | start번째부터 end-1번째까지 문자열을 반환한다. 이때, end 인덱스는 포함하지 않는다. ▷ var str = "Hello World"; console.log(str.substring(6, 11)); // World |
toLowerCase() | string을 소문자로 바꾼다. |
toUpperCase() | string을 대문자로 바꾼다. |
trim() | 문자열 양 끝의 빈 공백 문자를 제거한다. |
Objects - 내장객체 RegExp
RegExp
문자열에 대한 패턴을 정의하는 객체이다.
패턴 매칭(pattern-matching)을 통해 입력 형식을 제한할 수 있다.
패턴 매칭을 연습할 땐 아래 사이트를 이용해보도록 하자.
Regexper
regexper.com
※ Syntax
(1) RegExp 객체를 사용한 패턴 정의
var patt = new RegExp(pattern, modifiers);
(2) 문자열(string)을 사용한 패턴 정의
var patt = /pattern/modifiers;
※ 수정자(Modifiers)
Modifiers | Description |
i (ignore case) | 대소문자 구분 없이 매칭, 없으면 대소문자 구분함. 기본은 대소문자를 구분한다. |
g | 처음부터 전체에 걸쳐서 모든 일치하는 것 찾음. 기본은 처음으로 일치하는 것만 찾는다. ▷ const str = "blue sky, blue ocean, blue mountain"; console.log(str.match(/blue/)); // ['blue'] console.log(str.match(/blue/g)); // ['blue', 'blue', 'blue'] |
m | 여러 라인에 걸쳐서 매칭 ▷ const str = 'apple\nbanana\ncherry'; console.log(str.match(/^banana/)); // null. 문자열 전체의 시작에만 반응해서 두 번째 줄에 있어도 매칭 X console.log(str.match(/^banana/m)); // ['banana']. 각 줄의 시작도 인정 |
※ 괄호 (Brackets)
Expression | 설명 |
[abc] | 대괄호 내의 문자들을 찾음 |
[^abc] | 대괄호 내의 문자들을 제외한 문자들을 찾음 |
[0-9] | 0에서 9까지의 숫자 문자를 찾음 |
[A-Z] | 대문자 A부터 Z까지의 문자를 찾음 |
[a-z] | 소문자 a부터 z까지의 문자를 찾음 |
[A-z] | 대문자 A부터 소문자 z까지의 문자를 찾음 |
(red | blue | green) | 지정된 선택문자들 중 하나를 찾음 |
※ 메타문자 (Metacharacters)
Metacharacters | Description |
. | 줄 바꿈 또는 라인 끝 표시문자를 제외하고 단일 문자를 찾음 |
\w | 영문/숫자 문자를 찾음 |
\W | 영문/숫자 문자가 아닌 특수문자, 빈 공백 등의 문자를 찾음 |
\d | 숫자를 찾음 |
\D | 숫자가 아닌 문자를 찾음 |
\s | 공백 문자를 찾음 |
\S | 공백이 아닌 문자를 찾음 |
\b | 단어의 시작 또는 끝 부분에 일치하는 것을 찾음 ▶ 보통 단어의 시작 또는 끝 위치에 존재하는 패턴을 필터링할 때 사용한다. ▷ var str = 'cat catalog catch'; console.log(str.match(/cat\b/g)); // [ 'cat' ]. 단어의 끝 위치인 경우 필터링 console.log(str.match(/\bcat/g)); // [ 'cat', 'cat', 'cat' ]. 단어의 시작 위치인 경우 필터링 console.log(str.match(/\bcat\b/g)); // [ 'cat' ]. 딱 cat만 사용된 경우를 필터링 |
\B | 단어의 시작 또는 끝 부분이 아닌 부분에서 일치하는 것을 찾음. 즉, 단어의 처음이나 끝 부분이 아닌 곳에서 지정한 문자와 일치하는 문자를 찾음 ▶ 보통 단어 내부에만 존재하는 패턴을 필터링할 때 사용 ▷ var str = 'cat catalog catch'; console.log(str.match(/\Btal\B/g)); // [ 'tal' ]. 단어의 내부에 존재하는 경우 필터링 |
※ 수량 한정자 (Quantifiers)
Quantifier | Description |
n+ | 1개 이상의 n을 포함하는 문자열을 일치 (1 ≤ 개수) |
n* | 0개 이상의 n을 포함하는 문자열을 일치 (0 ≤ 개수) |
n? | 0 또는 1번의 n을 포함하는 문자열을 일치 (0 ≤ 개수 ≤ 1) |
n{X} | X번의 n을 포함하는 문자열을 일치 (개수 = X) |
n{X, Y} | X번에서 Y번의 n을 포함하는 문자열을 일치 (X ≤ 개수 ≤ Y) |
n{X, } | X번 이상의 n을 포함하는 문자열을 일치 (X ≤ 개수) |
n$ | n으로 끝나는 문자열을 일치 |
^n | n으로 시작하는 문자열을 일치 |
※ RegExp 객체 메서드
Method | 설명 |
패턴.exec(문자열) | 문자열에서 일치하는지를 검사하고 일치된 첫 번째를 반환 ▷ var str = 'Mr Blue has a blue house and a blue car'; var pattern = /blue/g; console.log(pattern.test(str)); // true |
패턴.test() | 문자열에서 일치하는지를 검사하고 true 또는 false를 반환 ▷ const pattern = /apple/i; // 대소문자 구분 안함 console.log(pattern.test('APPLE')); // true console.log(pattern.test('Apple')); // true console.log(pattern.test('aPpLe')); // true |
패턴.toString() | regular expression의 문자열 값로 변환하여 반환. ▷ const regex = /hello\d+/gi; console.log(regex.toString()); // 출력: "/hello\d+/gi". |
※ String 객체 메서드
Method | 설명 |
문자열.match(regexp) | regexp에 매치되는 문자열을 배열로 반환. 매치되는 문자열이 없으면 null을 반환 |
문자열.search(searchValue) | searchValue(또는 regexp) 문자열과 일치되는 position index를 반환 |
문자열.replace(searchValue, newValue) | searchValue(또는 regexp)와 일치되는 문자열을 newValue로 바꿈 |
Objects - BOM
BOM (Broswer Object Model)
브라우저에 내장된 객체로 브라우저 기능 제어가 가능하다.
최상위 객체는 window이며, 생략이 가능하다.
window 객체
브라우저의 최상위 객체이다.
Property | Description |
status | 브라우저의 상태 표시줄에 나타나는 문자열 |
defaultStatus | status의 초기 값 문자열 |
self | window 자기 자신 객체를 가리킨다. |
parent | window 객체 간의 계층 구조가 생길 때의 상위 객체를 말한다. |
top | window 객체 간의 계층 구조가 생길 때의 최상위 객체를 말한다. |
frames | 현재 window 내의 모든 <iframe> 요소를 반환한다. |
opener | open() 메서드로 오픈한 윈도의 부모 윈도 |
innerHeight, innerWidth | 윈도에서 내용이 나타나는 영역의 높이와 폭 |
outerHeight, outerWidth | 윈도의 전체 높이와 넓이 |
pageXOffset, pageYOffset | 현재 브라우저의 x 위치, y 위치 |
screen | window에 대한 screen 객체 반환 |
name | window의 이름 반환하거나 설정 |
document | window에 대한 Document 객체 반환 |
Method | Description |
alert(msg) | "확인" 버튼과 msg 문자열을 가지는 경고창 출력 |
confirm(msg) | "확인"과 "취소" 버튼, msg 문자열을 가지는 경고창 출력 |
prompt(text, defaultText) | 사용자로부터 입력 받는 질의/응답 창을 출력 |
open(URL, name, specs, replace) | 새로운 브라우저를 연다. |
close() | 열린 브라우저를 닫는다. |
setTimeout(str, time) | 지정된 시간 동안 기다린 후 명령어를 실행한다. 1번만 실행한다. ex) var tid = setTimeout("a()", 1000) |
clearTimeout(tid) | setTimeout() 해제한다. ex) clearTimeout(tid) |
setInterval(str, name) | 주기적인 명령 실행 ex) var tid = setInterval("함수()", 1/1000초 단위 시간) |
clearInterval(tid) | setInterval() 해제 ex) clearInterval(tid) |
moveBy(x, y) | 윈도의 위치에 상대적으로 이동한다. |
moveTo(x, y) | 윈도의 위치에 절대적으로 이동한다. |
resizeBy(width, height) | 윈도의 상대적 크기를 바꾼다. |
resizeTo(width, height) | 윈도의 절대적 크기를 바꾼다. |
scrollBy(xnum, ynum) | 윈도에 보여지는 부분을 상대적으로 스크롤한다. |
stop() | window loading을 중지시킴(브라우저의 stop 버튼 효과), IE 미지원 |
print() | 윈도에 포함된 내용을 출력한다. |
window.open() 메서드
※ Syntax
window.open(URL, name, specs, replace)
- URL: 오픈할 페이지의 URL
- name: window 이름 또는 _black, _parent, _self, _top
- replace: history list에 현재 문서를 URL로 갱신할지(true), 새로운 entry로 URL을 등록할지(false) 여부를 설정
- specs: 윈도우 모양 설정, 콤파(,)로 값 구분
specs options | Description |
fullscreen= yes | no | 1 | 0 | Whether or not to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode. IE only |
height=pixels | The height of the window. Min. value is 100 |
width=pixels | The width of the window. Min. value is 100 |
left=pixels | The left position of the window. Negative values not allowed |
top=pixels | The top position of the window. Negative values not allowed |
location= yes | no | 1 | 0 | Whether or not to display the address field. Opera Only |
menubar= yes | no | 1 | 0 | Whether or not to display the menu bar |
resizable= yes | no | 1 | 0 | Whether or not the window is resizable. IE only |
scrollbars= yes | no | 1 | 0 | Whether or not to display scroll bars. IE, Firefox & Opera only |
status= yes | no | 1 | 0 | Whether or not to add a status bar |
titlebar= yes | no | 1 | 0 | Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box. |
toolbar= yes | no | 1 | 0 | Whether or not to display the broswer toolbar. IE and Firefox only |
screen 객체
접속한 사용자 모니터의 해상도나 크기에 관한 정보를 가지고 있는 객체다.
Property | Description |
availHeight | Windows Taskbar를 제외한 화면 높이 |
availWidth | Windows Taskbar를 제외한 화면 너비 |
colorDepth | 이미지를 출력하기 위한 컬러 팔레트의 bit 깊이 |
height | 화면의 전체 높이 |
pixelDepth | 화면의 컬러 해상도(pixel당 bits) |
width | 화면의 전체 너비 |
location 객체
현재 URL에 대한 정보를 가지고 있는 객체이다.
Property | Description |
hash | URL의 해시(anchor)부분을 설정하거나 반환 |
host | URL의 호스트 이름(hostname)과 포트 번호(port)를 설정하거나 반환 |
hostname | URL의 호스트 이름을 설정하거나 반환 |
href | 전체 URL을 설정하거나 반환. 일반적인 페이지 이동 ▷ location.href = "https://example.com" |
origin | URL의 프로토콜, 호스트 이름, 포트 번호를 반환 |
pathname | URL의 경로를 설정하거나 반환 |
port | URL의 포트 번호를 설정하거나 반환 |
protocol | URL의 프로토콜을 설정하거나 반환 |
search | URL의 쿼리 문자열을 설정하거나 반환 |
assign() | 새로운 문서를 불러오기. 일반적인 페이지 이동 ▷ location.assign("https://example.com") |
reload() | 현재 문서를 새로고침 |
replace() | 현재 문서를 새 문서로 교체 (히스토리에 남지 않음). 히스토리 없이 강제 리다이렉트(예: 로그인 후) ▷ location.replace("https://example.com") |
history 객체
브라우저가 방문했던 URL 리스트 정보를 저장해 둔 객체이다.
Property | Description |
length | 히스토리 리스트에 저장된 주소의 개수 |
back() | 히스토리 리스트에서 한 단계 뒤의 주소로 이동 |
forward() | 히스토리 리스트에서 한 단계 앞의 주소로 이동 |
go(number) | 지정된 number 만큼 이동한 단계의 주소로 이동 (number가 음수일 경우 이전 단계 주소로, 양수일 경우 앞 단계 주소로 이동) |
navigator 객체
방문 사용자의 브라우저 정보를 담고 있는 객체이다.
Property | Description |
appCodeName | 브라우저의 code name 반환 |
appName | 브라우저 이름 반환 |
appVersion | 브라우저 버전 정보 반환 |
cookieEnabled | cookie가 브라우저에서 사용 가능한지 여부 (true: 사용 가능함) |
geolocation | 사용자의 지리적 위치가 저장된 Geolocation 객체 반환 |
language | 브라우저의 사용 언어 반환 |
onLine | 브라우저가 온라인 상태인지의 여부 (true: 온라인 상태) |
platform | 브라우저가 컴파일된 플랫폼 반환 |
product | 브라우저의 engine name 반환 |
userAgent | 브라우저에 의해 user-agent header가 서버로 전송되는 값 반환 |
javaEnabled() | 브라우저가 java를 지원하는지의 여부 (true: 자바를 지원함) |
Objects - DOM
DOM (Document Object Model)
웹 페이지가 로드될 때, 브라우저에 의해 생성된 문서 객체 모델을 말한다.
HTML DOM 모델은 객체에 대한 Tree로 구성된다.
HTML DOM은 HTML elements와 attributes를 접근하고, 변경시키고, 추가하고, 삭제하기 위한 표준 방법이다.
Finding HTML elements
Method | Description |
document.getElementById('id') | id 선택자로 지정된 element 객체 반환 |
document.getElementsByTagName('name') | 지정한 tag name에 해당하는 모든 element들을 array로 반환 |
document.getElementsByClassName('name') | 지정한 class name에 해당하는 모든 element들을 array로 반환 |
Changing HTML elements
Method | Description |
element.innerHTML = 'new html content' | element의 내부 content를 얻거나 설정 |
element.attribute = 'new value' | element의 attribute 값을 얻거나 설정 |
element.style.property = 'new style' | element의 style property를 설정 (CSS의 property) |
DOM을 사용하기 위한 호출 위치
기본 개념: 호출되기 전에 브라우저에 의해 객체가 인식되어야 한다.
◆ 방법 1: body 태그 로딩 후, 나중에 접근
<!DOCTYPE html>
<head>
</head>
<body>
<script>
calling JavaScript DOM;
</script>
</body>
</html>
◆ 방법 2: window의 onload 이후에 호출
<!DOCTYPE html>
<head>
<script>
window.onload = function() {
calling JavaScript DOM;
}
</script>
</head>
<body>
</body>
</html>
◆ 방법 3: event에 의해 나중에 접근 가능
<!DOCTYPE html>
<head>
<script>
function myEvent() {
calling JavaScript DOM;
}
</script>
</head>
<body>
<div onclick="myEvent()"></div>
</body>
</html>
※ Example: body 태그 로딩 전에, DOM을 통해 객체 접근이 불가능하다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var obj = document.getElementById('mydiv');
obj.innerHTML = "안뇽"
</script>
</head>
<body>
<div id="mydiv"></div>
</body>
</html>
대신 아래와 같은 코드로는 접근이 가능하다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
onload = function () {
var obj = document.getElementById('mydiv');
obj.innerHTML = "안뇽"
}
</script>
</head>
<body>
<div id="mydiv"></div>
</body>
</html>
Adding and Deleting Elements
Method | Description |
document.createElement(element) | HTML element를 생성한다. |
element.removeChild(element) | HTML element를 삭제한다. |
element.appendChild(element) | HTML element를 추가한다. |
element.replaceChild(element) | HTML element를 대체한다. |
Objects - DOM CSS
Changing CSS
※ Syntax
document.getElementById('id').style.property = 'your-style'
※ Style Object Properties
Property | Description |
backgroundColor | 요소의 배경색을 설정하거나 반환 |
border | 테두리 두께, 스타일, 색상을 한 번에 설정하거나 반환 |
color | 글자 색상을 설정하거나 반환 |
display | 요소의 display 유형을 설정하거나 반환 |
font | 글꼴 스타일, 두께, 크기, 줄 간격, 글꼴 종류 등을 한 번에 설정하거나 반환 |
margin | 요소의 margin을 설정하거나 반환 |
padding | 요소의 padding을 설정하거나 반환 |
position | 요소에 사용되는 위치 지정 방식을 설정하거나 반환 |
visibility | 요소를 보이게 할지 말지 여부를 설정하거나 반환 |
HTML DOM Select & Option Object
<select> element와 <option> element 객체를 나타낸다.
Property | Description |
disabled | 드롭다운 목록이 비활성화 되어 있는지 설정하거나 반환 |
length | 드롭다운 목록에 있는 <option> 요소의 개수를 반환 |
multiple | 다중 선택 가능 여부를 설정하거나 반환 |
selectedIndex | 드롭다운 목록에서 선택된 항목의 인덱스를 설정하거나 반환 |
size | 드롭다운 목록의 보이는 항목 수를 설정하거나 반환 |
value | 드롭다운 목록에서 선택된 항목의 값을 설정하거나 반환 |
add() | 드롭다운 목록에 새로운 옵션을 추가함 |
remove() | 드롭다운 목록에서 옵션을 제거함 |
※ Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function show() {
var obj = document.getElementById('car');
document.getElementById('result').innerHTML = obj.value + ", " + obj.selectedIndex
}
</script>
</head>
<body>
<select name="car" id="car">
<option value="현대">현대자동차</option>
<option value="기아">기아자동차</option>
<option value="벤츠">벤츠</option>
<option value="BMW">BMW</option>
</select>
<button type="button" onclick="show()">선택 값</button>
<br><br><br><br>
<p>선택된 값: <span id="result"></span></p>
</body>
</html>
▶ option의 첫 번째 인덱스 값은 0 임을 주의하자.
Option 객체의 속성과 메서드
Property | Description |
defaultSelected | selected 속성의 기본값(초기 선택 여부)를 반환 |
disabled | 해당 옵션이 비활성화 상태인지 설정하거나 반환 |
form | 이 옵션을 포함하고 있는 폼 요소에 대한 참조를 반환 |
index | 드롭다운 목록 내에서 옵션의 인덱스를 설정하거나 반환 |
label | 옵션의 label 속성 값을 설정하거나 반환 |
selected | 해당 옵션이 현재 선택되었는지 여부를 설정하거나 반환 |
text | 옵션 요소의 표시 텍스트를 설정하거나 반환 |
DOM Node Navigation
전체 문서는 document 노드이다.
모든 HTML element(tag)는 element 노드이다.
HTML elements 내의 텍스트는 text 노드이다.
모든 HTML 속성은 attribute 노드이다.
모든 주석은 comment 노드이다.
Properties
아래는 text, comment, whitespace, [Enter]를 하나의 node로 간주하는 속성을 나타낸 것이다.
Property / Method | Description |
element.childNodes | element의 자식 노드에 대한 collection 반환 |
element.firstChild | element의 첫 번째 자식 노드 반환 |
element.lastChild | element의 마지막 자식 노드 반환 |
element.parentNode | element의 부모 노드 반환 |
element.nextSibling | element의 형제 노드에서 다음 노드 반환 |
element.previousSibling | element의 형제 노드에서 이전 노드 반환 |
아래는 text, comment, whitespace, [Enter]를 하나의 node로 간주하지 않고, element 만을 지시하는 속성을 나타낸 것이다.
Property / Method | Description |
element.children | element의 자식 노드에 대한 collection 반환 |
element.firstElementChild | elementd의 첫 번째 자식 element 반환 |
element.lastElementChild | element의 마지막 자식 element 반환 |
element.parentElement | element의 부모 element 노드 반환 |
element.nextElementSibling | element의 형제 element에서 다음 element 반환 |
element.previousElementSibling | element의 형제 element에서 이전 element 반환 |
HTML Object - Collections
Property | Description |
document.anchors | 문서 내에서 name 속성이 있는 모든 <a> 요소들을 컬렉션 형태로 반환 |
document.embeds | 문서 내의 모든 <embed> 요소들을 컬렉션으로 반환 |
document.forms | 문서 내의 모든 <form> 요소들을 컬렉션으로 반환 |
document.images | 문서 내의 모든 <img> 이미지 요소들을 컬렉션으로 반환 |
document.links | 문서 내에서 href 속성이 있는 모든 <a> 및 <area> 요소들을 컬렉션으로 반환 |
document.scripts | 문서 내의 모든 <script> 요소들을 컬렉션으로 반환 |
DOM Events Handlers
DOM Event
※ Syntax
document.getElementById('id').onclick = function() {
// code
}
EventListener
HTML 요소 또는 window에 임의로 이벤트를 추가하거나 제거할 경우 사용한다.
한 요소에 같은 이벤트를 중복으로 등록할 경우 사용한다.
※ Syntax
element.addEventListener(event, function);
- event: on을 제거한 이벤트 이름
- function: 이벤트가 발생했을 때 호출하고자 하는 함수
◆ 방법 1:
element.addEventListener("click", function() { alert("Hello World!"); });
◆ 방법 2:
function myFunction() {
alert("Hello World!");
}
element.addEventListener("click", myFunction);
Event Object
※ Syntax
document.getElementById('id').onclick = function(e) {
var eventObj = e ? e : window.event; // IE8 이하에서는 window.event 객체 사용
// code
}
※ Event Object Attributes
구분 | Property | Description |
마우스 이벤트 | clientX | 마우스 이벤트가 발생한 X좌표(수평 스크롤 이동 너비 무시) |
clientY | 마우스 이벤트가 발생한 Y좌표(수직 스크롤 이동 너비 무시) | |
pageX | 마우스 이벤트가 발생한 X좌표(수평 스크롤 이동 너비 포함) | |
pageY | 마우스 이벤트가 발생한 Y좌표(수직 스크롤 이동 너비 포함) | |
screenX | 모니터 기준으로 마우스 이벤트가 발생한 X좌표 | |
screenY | 모니터 기준으로 마우스 이벤트가 발생한 Y좌표 | |
키보드 이벤트 | keyCode | 키보드에 눌린 유니코드 값 |
altKey | [Alt] 키가 눌리면 true, 아니면 false | |
ctrlKey | [Ctrl] 키가 눌리면 true, 아니면 false | |
전체 이벤트 | target | this와 같이 이벤트가 발생한 요소를 반환 |
JavaScript Exception Handling
Run-time 오류가 발생되었을 때의 예외를 제어한다.
※ Syntax
try {
// Block of code to try
} catch (err) {
// Block of code to handle errors
} finally {
// Block of code to be executed regardless of the try/catch result
}
※ Error Object Properties
Property | Description |
name | 에러 이름을 설정하거나 반환 |
message | 에러 메시지를 설정하거나 반환 |
throw
try~catch절에서 개발자가 error 내용을 생성하여 프로그램을 제어한다.
error 자료형은 String, Number, Boolean, Object가 될 수 있다.
try {
throw object; // 예외 발생시 object를 throw함
} catch(err) {
// Block of code to handle errors
}
throw "Too Big" // throw a text
throw 500; // throw a number
JavaScript Cookie
Cookie
저장이 필요한 정보가 생길 때 클라이언트 쪽에서 일정한 형식의 데이터를 저장하고 필요한 정보가 생길 때마다 서버에 저장된 정보를 전송한다.
클라이언트에 300개 이상, 호스트 또는 도메인 당 20개 이상 Cookie 생성이 가능하다.
또한, 각 Cookie 별로 Name 부여가 가능하며, 도메인당 10KBytes까지 저장이 가능하다(브라우저에 따라 4KBytes까지 저장).
※ Syntax
document.cookie = newCookie
Cookie 속성
Name=Value; expire=DATE; path=PATH; domain=DOMAIN_NAME; secure
- Name=Value: 쿠키를 구별하기 위함. 반드시 필요
- expire=DATE: 쿠키 유효 날짜 설정(Mon, DD-MM-YY, HH:MM:SS GMT)
- path=PATH: 쿠키가 유효한 경로 설정
- domain=DOMAIN_NAME: 쿠키가 유효한 도메인 설정
- secure: 연결이 안전할 때만 쿠키 전달(SSL을 사용하는 HTTPS 연결)
Cookie 보관 위치
윈도우 탐색기의 [폴더 옵션]에서 '보호된 운영 체제 파일 숨기기'를 check 해제하고, 숨김 파일, 폴더 및 드라이브 표시를 선택해야 한다.
(1) Internet Explorer(2022.06 Desktop버전 지원종료)
- Windows Vista & 7: C:\ Users\ <User ID>\ AppData\ Roaming\ Microsoft\ Windows\ Cookies
- Windows 8 & 8.1 & 10: C:\ Users\ <User ID>\ AppData\ Local\ Microsoft\ Windows\ INetCookies
(2) Microsoft Edge: C:\ Users\ <User ID>\ AppData\ Local\ MicrosoftEdge\ User\ Default (물리적 저장위치)
- SQLite 데이터베이스 파일로 인코딩되어 관리됨
- 엣지 브라우저 주소입력 줄에 “edge://settings/siteData” 입력하여 확인
(3) Chrome: C:\ Users\ <User ID>\ AppData\ Local\ Google\ Chrome\ User Data\ Default (물리적 저장위치)
- SQLite 데이터베이스 파일로 인코딩되어 관리됨
- 크롬 브라우저 주소입력 줄에 “chrome://settings/siteData” 입력하여
'대학 강의 > 인터넷 프로그래밍' 카테고리의 다른 글
인터넷 프로그래밍 개요 (0) | 2025.03.24 |
---|---|
CSS3 (0) | 2025.03.23 |
HTML5 기본 (0) | 2025.03.17 |