2024-06-21

This commit is contained in:
2024-06-21 14:34:12 +09:00
parent ca239cf362
commit 342a843ce6
23 changed files with 2654 additions and 1 deletions

43
Writerside/topics/Ajax.md Normal file
View File

@@ -0,0 +1,43 @@
# AJAX
```javascript
let request = new XMLHttpRequest();
request.open("GET", "http://www.example.com/");
request.onreadystatechange = function () {
if (this.readyState === 4 && request.status === 200) {
let result = JSON.parse(request.responseText);
}
};
request.send();
```
- open()
- setRequestHeader()
- responseType
- attaybuffer
- blob
- document
- json
- text
- timeout
- onreadystatechange
- UNSENT : 0
- OPENED : 1
- HEADERS_RECEIVED : 2
- LOADING : 3
- DONE : 4
- status, statusText
- send()
- response, responseText, responseURL, responseXML
```javascript
let request = new XMLHttpRequest();
request.open("POST", "http://www.example.com/");
request.responseType = "json";
request.onreadystatechange = function () {
if (this.readyState === DONE && request.status === 200) {
let result = request.response;
}
};
request.send(JSON.stringify({message : "Hello"}));
```

View File

@@ -0,0 +1,64 @@
# Typed Array
타입 배열은 이진 데이터를 빠르게 처리하기 위한 버퍼와 뷰로 구성됩니다.
```javascript
let buffer = new ArrayBuffer(16); // 16바이트 크기의 버퍼
let intView = new Int32Array(buffer); // 4바이트 정수형 뷰
for (let i = 0; i < intView.length; i++) {
intView[i] = i * 2;
}
let byteView = new Uint8Array(buffer); // 동일한 버퍼에 대한 1바이트 뷰
for (let i = 0; i < byteView.length; i++) {
console.log(byteView[i]);
}
```
# Map
```javascript
let map = new Map();
map.set("name", "Charlie");
map.set("age", 14);
for (let [key, value] of map) {
console.log(key + " : " + value);
}
```
```javascript
get()
set()
has()
delete()
size
```
# Set
```javascript
let set = new Set();
set.add(1);
set.add(3);
for (let item of set) {
console.log(item);
}
```
```javascript
add()
has()
delete()
size
```
## 배열과 상호 변환
```javascript
let array = Array.from(set);
let set = new Set(array);
```

View File

@@ -0,0 +1,90 @@
# 배열
## 배열의 생성
```javascript
let array1 = ["a", "b", "c"];
let array2 = new Array("a", "b", "c");
let array3 = Array("a", "b", "c");
let array4 = Array(3); // [,,] 길이가 3인 배열
let array4 = Array.of(3); // [3] ECSMScript 2015
```
## 인덱스
자바스크립트의 배열은 0부터 시작하는 인덱스를 사용합니다.
## 배열의 길이
```length```는 메서드가 아니라 속성입니다. 읽기뿐만 아니라 쓰기도 할 수 있으며 length에 0을 할당하면 크기가 0인 배열이 됩니다.
```javascript
let array = ["a", "b", "c"];
console.log(array.length);
```
## 반복
```javascript
let array = ["a", "b", "c"];
/* C 스타일의 for 루프 */
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
/* for .. of */
for (const item of array) {
console.log(item);
}
/* for each */
array.forEach(function (item) {
console.log(item);
});
/* for each with arrow function */
array.forEach((item) => console.log(item));
/* map */
array.map((item, idx)=>{
console.log(item);
});
```
## 메서드
```javascript
concat()
join()
push()
pop()
shift()
unshift()
slice()
splice()
reverse()
sort()
indexOf()
lastIndexOf()
```
```javascript
forEach()
map()
filter()
every()
some()
reduce()
reduceRight()
```
## 배열의 해체
```javascript
let array = ["a", "b", "c"];
let [a, b] = array;
console.log(a);
console.log(b);
```

View File

@@ -0,0 +1,212 @@
# BOM
- innerWidth, innerHeight
뷰포트의 크기. 스크롤바 포함
- outerWidth, outerHeight
브라우저의 크기
- scrollX = pageXOffset, scrollY = pageYOffset
스크롤된 픽셀 크기
- screenX = screenLeft, screenY = screenTop
모니터 좌표 (0, 0)에서부터 뷰포트 까지의 픽셀 거리
- open()
- close()
- moveTo()
- moveBy()
- resizeBy()
- resizeTo()
- scroll(option)
```javascript
window.scroll({top:100, left:100, behavior:"smooth"});
```
- scrollBy(x, y)
- scrollTo(x, y)
- addEventListener(eventType, listener)
```javascript
window.addEventListener('DOMContentLoaded', (event) => {
//
});
```
- removeEventListener(eventType, listener)
## 대화상자
- alert(message)
알림 대화상자
- confirm(message)
확인 대화상자. true/false를 반환
- prompt(message)
입력 대화상자. 사용자가 입력한 텍스트를 반환하거나 null을 반환
## 타이머
- setTimeout(callback, ms)
지연 시간 이후에 함수를 실행. 고유아이디를 반환.
- setInterval(callback, ms)
지연 시간마다 함수를 반복 실행. 고유아이디를 반환.
- clearTimeout(id)
- clearInterval(id)
```javascript
let uId = setInterval(() => {
document.querySelector('#box').innerHTML = new Date();
}, 1000); // 1초마다 새로 고침
setTimeout(() => {
clearInterval(uId);
}, 5000); // 5초 후에 새로 고침 중단
```
## Console
- log(message)
- debug(message)
- info(message)
- warn(message)
- error(message)
- assert(expression, message)
매개 변수가 false인 경우에 메시지와 함께 스택 추적을 출력합니다.
- clear()
콘솔의 출력을 지웁니다.
- trace()
콘솔에 스택 추적을 출력합니다.
- table(obj)
배열이나 객체 등을 콘솔에 표 형태로 출력합니다.
## History
- length
방문 기록에 저장된 페이지 갯수
- back()
뒤로 가기
- forward()
앞으로 가기
- go(number)
number가 0이면 새로 고침. -2이면 2 페이지 뒤로 가기.
## Screen
- width, height
모니터 화면의 전체 픽셀 크기
- availWidth, availHeight
작업표시줄 등을 제외한 모니터 크기
- pixelDepth
- colorDepth
```javascript
function getScreenSize(){
return {
width: window.screen.width,
height: window.screen.height
};
}
```
## Location
- href
현재 페이지의 URI
- protocol, host, hostname, port, pathname, search, hash
URI 중 특정 부분
- assign(uri)
다른 페이지로 이동
- replace(uri)
다른 페이지로 이동. 히스토리를 남기지 않습니다.
- reload()
새로 고침. 매개 변수로 true를 전달하면 강력 새로 고침.
## Navigator
- onLine
온라인 여부를 true / false로 반환
- cookieEnabled
쿠키 사용 가능 여부
- language
- appName, appVersion, appCodeName, platform
- userAgent
- javaEnabled
```javascript
function isConnected() {
return navigator.onLine;
}
window.addEventListener("online", function () {
console.log("연결됨");
});
window.addEventListener("offline", function () {
console.log("연결 끊김");
});
```

View File

@@ -0,0 +1,84 @@
# 캔버스
```html
<!doctype html>
<html>
<head>
<title>Test</title>
<script>
window.addEventListener("DOMContentLoaded", () => {
const canvas = document.querySelector('canvas');
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight;
const g = canvas.getContext("2d");
g.fillStyle = 'rgb(0, 0, 0)';
g.fillRect(10, 10, 100, 200);
g.strokeStyle = 'red';
g.lineWidth = 1;
g.strokeRect(20, 20, 200, 200);
});
</script>
</head>
<body style="margin:0; overflow: hidden;">
<canvas id="canvas" style="background-color: antiquewhite;">
</canvas>
</body>
</html>
```
- fillStyle
- strokeStyle
- lineWidth
- lineCap
- lineJoin
- font
- textAlign
- textBaseline
- shadowBlur, shadowColor, shadowOffsetX, shadowOffsetY
- fillRect(x, y, w, h)
- strokeRect(x, y, w, h)
- clearRect(x ,y, w, h)
## Path
- beginPath()
- moveTo(x, y)
- lineTo(x, y)
- arc(x, y, radius, startAngle, endAngle, anticlockwise)
- arcTo(x,y,x,y,radius)
- bezierCurveTo(x,y,x,y,x,y)
- quadraticCurveTo(x,y,x,y)
- fill()
- stroke()
- closePath()
## Text
- strokeText(str, x, y)
- fillText(str, x, y)
- measureText(str)
## Image
```javascript
let image = new Image();
image.src = 'myimage.png';
image.onload = function(){
g.drawImage(image, 100, 100);
}
```
## 캔버스
- save()
- restore()
- rotate()
- scale()
- translate()
- transform()

View File

@@ -0,0 +1,274 @@
# 기본 문법과 자료형
## 기본 구문
자바스크립트의 구문은 자바, C, C++ 등과 매우 비슷합니다.
```javascript
let a = "Hello";
let 안녕 = "안녕";
```
자바스크립트는 대소문자를 구분합니다. 또한, 유니코드를 사용하므로 변수 이름에 한글을 사용해도 됩니다.
자바와 마찬가지로, 하나의 명령문이 끝나면 세미콜론을 붙입니다. 하지만, 줄 바꿈이 있는 때에는 세미콜론을 생략해도 됩니다.
C 스타일의 한줄 주석과, C++ 스타일의 블록 주석 모두 사용할 수 있습니다.
## 변수의 선언
- var
변수를 선언합니다. 선언과 동시에 값을 할당할 수도 있습니다. 하위호환성 문제가 없다면 `let``const`를 사용하세요.
- let
변수를 선언합니다. `var`의 단점을 보완하고자, ECMAScript 2015에서 추가되었습니다.
- const
상수를 선언합니다. ECMAScript 2015에서 추가되었습니다.
상수의 값은 변경할 수 없지만, 상수로 선언된 객체의 멤버나 상수로 정의된 배열의 항목은 변경할 수 있습니다.
선언만하고 초기화되지 않은 변수는 ```undefined```라는 값을 갖습니다.
```javascript
let a;
console.log("a = " + a); // a = undefined
const PI = 3.141592;
```
### var와 let
#### 변수의 범위
`var`로 선언된 변수는 블록 범위라는 개념이 없습니다.
```javascript
if (true) {
var a = "Hello";
}
console.log(a); // Hello
```
`let`으로 선언된 변수는 블록 범위 내에서만 유효합니다.
```javascript
if (true) {
let a = "Hello";
}
console.log(a); // ReferenceError: a is not defined
```
#### 변수 호이스팅
`var`로 선언된 변수는 맨 위로 끌어 올려집니다.
```javascript
console.log(a === undefined); // 나중에 선언된 변수도 사용할 수 있다.
var a = 3;
/* 위 코드는 아래와 같이 작동합니다. */
var a;
console.log(a === undefined);
a = 3;
```
```javascript
console.log(a === undefined); // ReferenceError: Cannot access 'a' before initialization
let a = 3;
```
#### 함수 호이스팅
```javascript
fun1(); // 아직 정의되지 않은 함수도 맨 위로 끌어 올려집니다.
function fun1() {
console.log("Function 1");
}
fun2(); // Error
var fun2 = function () { // 함수 표현식 형태로 정의된 경우에는 끌어 올려지지 않습니다.
console.log("Function 2");
}
```
## 데이터 구조와 타입
- Boolean
true 또는 false 중 하나입니다.
- Number
정수형 또는 실수형 숫자입니다.
- String
문자열입니다.
- Symbol
인스턴스가 고유하고 불변인 데이터 형입니다. ECMAScript 2015에서 추가되었습니다.
- Object
자바스크립트 객체입니다.
- undefined
undefined는 수치 문맥에서는 NaN으로, boolean 문맥에서는 false로 동작합니다.
```javascript
let a; // a = undefined
if (a) {
console.log("a = " + a);
} else {
console.log("a is undefined.");
}
console.log(a + 34); // NaN
```
- null
자바스크립트는 대소문자를 구분하므로 `null`은 Null, NULL 등과 다릅니다.
`null`은 수치 문맥에서는 `0`으로, boolean 문맥에서는 `false`로 동작합니다.
```javascript
let a = null;
if (a) {
console.log("a = " + a);
} else {
console.log("a is null.");
}
console.log(a + 34); // 34
```
### 동적 자료형
자바스크립트는 동적 타이핑 언어로써 변수에 자료형을 지정하지 않습니다.
```javascript
let a = 43;
a = "Hello"; // 숫자나 문자열이나 상관없이 어떤 값이라도 할당할 수 있습니다.
```
문자열과 숫자를 + 연산하면 숫자는 문자열로 변환됩니다. 그러나, - 연산의 경우에는 문자열형 숫자가 숫자로 변환됩니다.
```javascript
console.log("The number is " + 42); // The number is 42
console.log(42 + " is the number"); // 42 is the number
console.log("The number is " - 42); // NaN
```
```javascript
console.log("3" + 2); // 32
console.log(3 + "2"); // 32
console.log("3" + "2"); // 32
console.log("3" - 2); // 1
console.log(3 - "2"); // 1
console.log("3" - "2"); // 1
```
### 문자열형 숫자를 숫자로 변환
전역 함수 parseInt()와 parseFloat()를 사용해서 문자열형 숫자를 숫자로 바꿀 수 있습니다.
```javascript
parseInt(numStr, radix) // 진법도 지정해야 합니다.
parseFloat(numStr)
```
```javascript
let a = "3.9";
console.log(parseInt(a, 10)); // 3
console.log(parseFloat(a)); // 3.9
```
## 리터럴
### 숫자
```javascript
43, -365 // 10진수
0xff0d, 0x1234 // 16진수. 0x로 시작한다.
0b0011, -0b11 // 2진수. 0b로 시작한다.
3.141592 // 실수
-.1234
-3.1E+12 // 실수의 지수 표현
.1e-23
```
### 문자열
문자열은 큰 따옴표("") 또는 작은 따옴표('')로 감싸서 표현합니다.
```javascript
let str = "Hello, World!";
```
#### 템플릿 리터럴
템플릿 리터럴은 ECMAScript 2015에서 추가되었습니다. 템플릿 문자열은 백틱(`)으로 감쌉니다. 템플릿 문자열에서는 줄 바꿈이 유지됩니다.
```javascript
let name = "Charlie";
let age = 14;
let template = `My name is ${name}. I'm ${age}-year-old.`;
console.log(template);
```
### 배열
배열은 대괄호를 사용해서 표현합니다.
```javascript
let array = ["a", "b", "c"];
```
배열 요소 가운데에 쉼표만 있으면 해당 요소는 undefined가 됩니다. 맨 끝의 쉼표는 무시됩니다만, 브라우저에 따라 다르게 구현되어 있습니다.
```javascript
let array = ["a", "b", , "c",];
for (const element of array) {
console.log(element);
}
/*
a
b
undefined
c
*/
```
### 객체
객체는 중괄호를 사용해서 키/값 쌍을 표현합니다.
```javascript
let charlie = {
age: 14,
name:"Charlie"
};
console.log(charlie.age); // C의 구조체처럼 .으로 접근할 수도 있고,
console.log(charlie["age"]); // 배열처럼 []로 접근할 수도 있습니다.
```
### 정규식
정규식은 슬래시로 감싸서 표현합니다.
```javascript
let regex = /[a-z0-9]*/;
```

24
Writerside/topics/Date.md Normal file
View File

@@ -0,0 +1,24 @@
# 날짜
자바스크립트에는 날짜와 관련된 자료형이 없으며, Date를 사용해서 Epoch(1970-1-1T0:00:00UTC) 이후로 경과된 밀리초를 사용해서 날짜를 처리합니다.
## Date
```javascript
Date.now() // Epoch로부터 경과 시간을 밀리초로 반환합니다.
Date.parse(dateString) // 문자열을 밀리초로 변환합니다.
Date.UTC(y, m, d, h, m, s, ms) // UTC 기준 밀리초로 변환합니다.
```
```javascript
setXXX() // 함수, 날짜 개체 안에서의 날짜 및 시간 값을 설정합니다.
getXXX() // 함수, 날짜 개체 안에서의 날짜 및 시간 값을 얻습니다.
toXXX() // 함수, 날짜 개체로부터 문자열 값을 반환합니다.
```
```javascript
let now = new Date(); // now
let date1 = new Date(0); // millisec from epoch
let date2 = new Date("2020-01-01T00:30:00"); // date string
let date3 = new Date(2020, 1, 1, 0, 30, 0); // y m d h m s ...
```

View File

@@ -0,0 +1,174 @@
# DOM
- documentElement
\<html> 요소를 반환
- head
\<head> 요소를 반환
- body
\<body> 요소를 반환
만일, \<head>에 포함된 스크립트에서 body를 호출한다면 body는 null이 되므로 주의해야 합니다.
- getElementById()
- getElementsByClassName()
- getElementsByTagName()
- querySelector()
- querySelctorAll()
- anchors
- characterSet
- docType
- documentURI
- embeds
- fonts
- forms
- images
- links
- childElementCount
- children
- firstElementChild
- lastElementChild
- title
- referrer
- URL
- location
- createElement()
- createTextNode()
- createAttribute()
- append()
- prepend()
## Node
- childNodes
- firstChild
- lastChild
- nextSibling
- previousSibling
- parentNode
- parentElement
- nodeType
- nodeValue
- textContent
- appendChild()
- insertBefore()
- cloneNode()
- removeChild()
- replaceChild()
- contains()
- hasChildNodes()
## Element
- id
- tagName
- attributes
- innerHTML
- outerHTML
- classList
- className
- clientWidth, clientHeight
- clientTop, clientLeft
- scrollWidth, scrollHeight
- scrollTop, scrollLeft
- addEventListener()
- removeEventListener()
- getAttribute()
- getAttributeNames()
- setAttribute()
- hasAttribute()
- removeAttribute()
- getElementById()
- getElementsByClassName()
- getElementsByTagName()
- querySelector()
- querySelectorAll()
- insertAdjacentElement()
- insertAdjacentHTML()
- beforebegin
- afterbegin
- beforeend
- afterend
```javascript
el.insertAdjacentHTML("beforeend", "<p>Hello~</p>");
```
- insertAdjacentText()
- remove()
- requestFullScreen()
- scroll()
- scrollBy()
- scrollIntoView()
- scrollTo()
## 클래스
```javascript
let classes = document.querySelector('div').classList;
classes.add("myclass", "myclass-2");
classes.remove("myclass-2");
classes.replace("myclass", "myclass-1");
classes.toggle("hidden");
```
## 스타일
```javascript
let el = document.querySelector('p');
el.style.color = "red";
```
## 속성
```javascript
let el = document.querySelector('a');
el.getAttribute("href");
el.setAttribute("href", "...");
el.removeAttribute("href");
```
## 자식 요소 추가
```javascript
let el = document.querySelector('div');
let p = document.createElement("p");
let text = document.createTextNode("Hello");
p.appendChild(text);
el.appendChild(p);
```
```javascript
el.innerHTML = "<p>Hello~</p>";
el.insertAdjacentHTML("beforeend", "<p>Hello~</p>");
```

View File

@@ -0,0 +1,134 @@
# 흐름 제어
## 조건문
자바스크립트의 조건문은 자바나 C의 조건문과 같습니다.
```javascript
if (조건식) { ... }
```
```javascript
if (조건식) { ... } else { ... }
```
```javascript
if (조건식) { ... } else if (조건식) { ... } else { ... }
```
자바스크립트에서는 다음의 값은 거짓으로 평가되며 그 외에는 참으로 평가됩니다.
- false
- undefined
- null
- 0
- NaN
- ""
빈 문자열.
Boolean 객체의 값이 false인 경우라도, 조건식에서는 true로 평가됩니다. 주의하세요.
```javascript
let a = new Boolean(false);
if (a) {
console.log("yes"); // 여기가 실행됩니다.
} else {
console.log("no");
}
```
```javascript
switch (표현식) { case: ... break; default: ... break; }
```
## 반복문
기본적인 반복문은 C 스타일의 반복문과 같습니다.
```javascript
for (초기식;조건식;증감식) { ... }
```
```javascript
while (조건식) { ... }
```
```javascript
do { ... } while (조건식);
```
```javascript
break;
```
```javascript
continue;
```
### for … in
객체의 속성을 통해서 반복합니다.
```javascript
let charlie = {
age: 14,
name: "Charlie"
};
for (let prop in charlie) {
console.log(prop + " = " + charlie[prop]);
}
```
### for … of
배열 등 반복 가능한 객체를 반복합니다.
```javascript
let array = [1, 2, 3, 4, 5];
for (let item of array) {
console.log(item);
}
```
## 예외 처리
예외 처리 구문은 자바의 예외 처리 구문과 비슷합니다.
```javascript
try { ... } catch(e) { ... }
try { ... } catch(e) { ... } finally { ... }
```
try 블록을 실행하는 도중 예외가 발생하면, catch 블록으로 넘어갑니다.
catch문에서는 throw 구문에서 던진 객체를 받을 수 있습니다.
try 블록이 성공하든 실패하든 finally 블록은 무조건 실행됩니다. 만일, finally 블록에서 return으로 값을 반환하는 경우에, try 블록이나 catch 블록의 return 값은 무시됩니다.
```javascript
throw 표현식;
```
예외를 발생시킬 때 사용합니다. 객체, 숫자, 문자열 등 무엇이든 던질 수 있습니다.
```javascript
function fun1() {
throw { code: 1, message: "Error" };
}
try {
fun1();
} catch (e) {
console.warn(e.message);
} finally {
console.log("The End");
}
```

View File

@@ -0,0 +1,235 @@
# 함수
자바스크립트의 함수 정의는 C 스타일의 함수 정의와 유사합니다. 반환 자료형이 없으며, function이라는 키워드를 사용합니다.
매개 변수가 기본자료형인 경우에는 값이 전달됩니다. 그러나, 매개 변수가 배열이나 객체인 경우에는 그 속성의 변화가 함수 외부에서도 유효합니다.
모든 자바스크립트 함수는 값을 반환합니다. return 문을 통해 명시적으로 값을 반환하지 않는 함수는 undefined를 반환합니다.
```javascript
function myFunction(param) {
return param * 2;
}
```
## 함수 표현식
자바스크립트에서는 함수 또한 객체이기 때문에 다음과 같은 표현도 가능합니다.
```javascript
let myFunction = function (param) {
return param * 2;
};
```
함수 표현식을 사용하면 함수를 동적으로 만들 수 있습니다.
```javascript
let myFunction;
if (a > 0) {
myFunction = function (param) {
return param * 2;
};
} else {
myFunction = function (param) {
return param * 4;
};
}
```
## 중첩된 함수
함수 안에서 또 다른 함수를 정의하는 것도 가능합니다. 내부 함수는 외부 함수 안에서만 접근할 수 있습니다. 내부 함수에서는 외부 함수의 변수와 매개 변수에 접근할 수 있습니다.
```javascript
function addSquare(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
console.log(addSquare(2, 3)); // 13
```
```javascript
function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}
let fnInside = outside(3);
console.log(fnInside(5)); // 8
console.log(outside(3)(5)); // 8
```
위와 같이 난해한 문법도 가능합니다.
## 클로져
자바스크립트의 함수는 중첩될 수 있다는 위의 특징을 활용하면, 다음과 같은 코드도 만들어 집니다.
```javascript
let Person = function (name) {
let age;
return {
getAge: function () {
return age;
},
setAge: function (newAge) {
age = newAge;
},
getName: function () {
return name;
},
setName: function (newName) {
name = newName;
}
}
};
let charlie = Person("charlie");
charlie.setAge(14);
charlie.setName("Charlie");
console.log(charlie.getName());
```
## 매개변수
함수에 전달되는 매개 변수는 매개 변수 이름을 직접 참조할 수도 있지만, ```arguments```를 통해서 배열과 같은 방식으로도 처리할 수 있습니다.
```javascript
function func1(param1, param2) {
for (let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
func1("A", "B");
```
이러한 특징을 활용하면, 임의 길이 매개 변수를 처리할 수 있습니다.
```javascript
function add() { // 함수 정의 부분의 매개 변수 항복은 별 의미가 없어집니다.
let sum = 0;
for (let i of arguments) {
sum += i;
}
return sum;
}
console.log(add(1, 2, 3, 4, 5));
```
### 매개 변수의 기본값
함수 호출시에 생략된 매개 변수는 기본값인 undefined를 갖습니다.
```javascript
function myFunction(a, b) {
console.log("a = " + a);
console.log("b = " + b);
}
myFunction(1);
/*
a = 1
b = undefined
*/
```
ECMAScript 2015에서는 매개 변수의 기본값을 지정할 수 있습니다.
```javascript
function myFunction(a, b = 3) {
console.log("a = " + a);
console.log("b = " + b);
}
myFunction(1); // 생략된 매개 변수 b는 기본값이 3이 됩니다.
```
### 나머지 매개 변수
ECMAScript 2015에서는 임의 길이 매개 변수 기능이 추가되었습니다. 매개 변수 이름 앞에 ```…```을 붙입니다.
```javascript
function sum(...args) {
let sum = 0;
args.forEach(function (val) {
sum += val;
});
return sum;
}
console.log(sum(1, 2, 3, 4, 5));
```
## 화살표 함수
위의 코드는 다음과 같이 짧게 줄일 수 있습니다.
```javascript
function sum(...args) {
let sum = 0;
args.forEach((val) => sum += val);
return sum;
}
```
## 미리 정의된 전역 함수
```javasc
eval()
```
문자열로 표현된 자바스크립트 코드를 실행합니다.
```javascript
inFinite()
```
매개 변수로 전달된 값이 유한한지 확인합니다.
```javascript
isNaN()
```
NaN인지 확인합니다. Number.isNan() 또는 typeof를 대신 사용하는 것이 좋습니다.
```javascript
parseFloat()
```
문자열을 실수로 바꿉니다.
```javascript
parseInt()
```
문자열을 정수로 바꿉니다.
```javascript
encodeURI()
encodeURIComponent()
decodeURI()
decodeURIComponent()
```
URI를 UTF-8 이스케잎 문자로 (또는 그 반대로) 변환합니다.
```javascript
let uri = "https://www.elex-project.com/test?a=몰라&b=알수가없어";
console.log(encodeURI(uri));
console.log(encodeURIComponent(uri));
/*
https://www.elex-project.com/test?a=%EB%AA%B0%EB%9D%BC&b=%EC%95%8C%EC%88%98%EA%B0%80%EC%97%86%EC%96%B4
https%3A%2F%2Fwww.elex-project.com%2Ftest%3Fa%3D%EB%AA%B0%EB%9D%BC%26b%3D%EC%95%8C%EC%88%98%EA%B0%80%EC%97%86%EC%96%B4
*/
```

View File

@@ -0,0 +1,23 @@
# Iterator
```javascript
function* myIterator(start = 0, end = Infinity, step = 1) {
let n = 0;
for (let i = start; i < end; i += step) {
n++;
yield i;
}
return n;
}
for (let item of myIterator(0, 10)) {
console.log(item)
}
let it = myIterator(0, 10);
let item = it.next();
while (!item.done) {
console.log(item.value);
item = it.next();
}
```

View File

@@ -0,0 +1,555 @@
# JavaScript Cheatsheet
## Table of Contents
[Basics](#basics)
[Arrays & Objects](#arrays--objects)
[Functions](#functions)
[Recursive Functions](#recursive-functions)
[Methods](#methods)
[Predefined Functions/Methods](#predefined-functionsmethods)
- [On Strings](#on-strings)
- [On Arrays](#on-arrays)
- [Nodes](#nodes)
[Custom Constructors / Classes](#custom-constructors--classes)
[Math](#math)
[Loops](#loops)
[Logical Operators](#logical-operators)
- [Conditional Operator](#conditional-operator)
[User Input](#user-input)
[JSON](#json)
[ES6](#es6)
[Tricks](#tricks)
- [Get Password Combinations](#get-password-combinations)
## Basics
`&&`: and
`||`: or
`!`: not
`1`: true
`0`: false
**increments:**
i++ , i-- , i += x , i -= x
**isNaN('berry');** true returns true when not a number
**isNaN(42);** false
x**.length** Returns the length of a string or the amount of items in a variable
**typeof** variable returns object, number, string
**Z < a** true, uppercase < lowercase
```javascript
// In browsers, the global scope object is stored in the window variable:
var myVar = 10; // global variable
console.log("myVar" in window); // true
console.log(window.myVar); // 10
```
## Arrays & Objects:
```javascript
var newArray = []; // could do variable = [1,2,3] as well
newArray.push('hello');
newArray[0]; // equals hello;
var newObject = {
key: value,
key: value
} // object literal notation
// Each piece of information we include in an object is known as a property. Each Property has a Value
var myObj = new Object(); // object constructor
myObj["key"] = "value"; // or myObj.key = "value";
delete newObject.key; // removes the key (very uncommon)
console.log("key" in anObject); // "in" returns a Boolean value that indicates whether that object has that property
myObj.hasOwnProperty('name') // returns true if myObj has a name property
```
## Functions:
```javascript
var newFunction = function(argument,argument) { }; // or function newFunction(){} = function declarations = not part of the regular top-to-bottom flow = only use this form in the outermost block of a function or program.
newFunction(x,y);
// below are 3 new things for functions in JavaScript 6 (experimental for now)
argument => argument + 1; // is equal to function(argument){ return argument + 1; };
function(x = 7, y = 42) { } // to set default values
function(x, y, ...a) { } // ...a will store all the
var newFunction = function() { return "hi" };
newFunction // returns the function while newFunction() would return the functions outcome.
```
## Recursive Functions
```javascript
// Functions calling themselves (create a kindof finite loop)
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1); // dont forget to return your recursion else, youll get an undefined.
}
console.log(power(2, 3));
// → 8
```
Simplest example:
```javascript
(function loop(base, i){
// do something
if(i>0) return loop(base, i-1); // loop
})(["a", "b"], length)
```
```javascript
/*
* Whenever a function is called, a special variable named arguments is added to the environment in which the function body runs.
*/
function argumentCounter() {
console.log("You gave me", arguments.length, "arguments.");
}
argumentCounter("Straw man", "Tautology", "Ad hominem"); // You gave me 3 arguments.
```
## Methods:
```javascript
var bob = new Object();
bob.age = 17; // or: bob["age"] = 17; this way you can use variables as well: bob[variable];
bob.setAge = function (newAge){ bob.age = newAge; };
bob.setAge(5); // would set the Age Property of bob to 5 using the respective function
// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) { this.age = newAge; };
var bob = { age: 25, setAge: setAge }
bob.setAge(50);
// writing an object constructor or object literal notation both work the same
function someObject() {
this.stuff = "bla"
this.someMethod = function() { console.log(this.stuff) };
}
// Associate methods to properties
var pile = {
elements: ["eggshell", "orange peel", "worm"],
get height() {
return this.elements.length;
},
set height(value) {
console.log("Ignoring attempt to set height to", value);
}
};
// the get and set notation for properties allows you to specify a function to be run when the property is read or written
console.log(pile.height); // → 3
pile.height = 100; // → Ignoring attempt to set height to 100
// You can also add such a property to an existing object, for example a prototype, using the Object.defineProperty function
function Pile() {
this.elements = ["eggshell", "orange peel", "worm"];
}
Object.defineProperty(Pile.prototype, "height", {
get: function() { return this.elements.length; }
});
var test = new Pile();
console.log(test.height); //-> 3
```
## Predefined Functions/Methods
### On Strings
```javascript
/*
* toUpperCase, toLowerCase, trim, charAt
*/
"Doh".toUpperCase() // "DOH"
"Doh".toLowerCase() // "doh"
" okay \n ".trim() // "okay"
"bla".charAt(0) // b identical to "bla"[0]
/*
* Repeat
*/
'-'.repeat(2); //-> '--' (not supported by IE and Opera)
```
### On Arrays
```javascript
/*
* Push, Pop, shift and unshift
*/
var mack = [];
mack.push("Mack");
mack.push("the", "Knife");
mack; // → ["Mack", "the", "Knife"]
mack.join(" "); // → Mack the Knife
mack.pop(); // → Knife
mack; // → ["Mack", "the"]
// push and pop add or remove elements at the end of an array
// shift and unshift add or remove elements at the start of an array
/*
* indexOf, lastIndexOf
*/
[1, 2, 3, 2, 1].indexOf(2); // → 1
[1, 2, 3, 2, 1].lastIndexOf(2); // → 3
/*
* slice & concat
*/
[0, 1, 2, 3, 4].slice(2, 4); // → [2, 3] (positions 2,4 2 included 4 excluded)
[0, 1, 2, 3, 4].slice(2); // → [2, 3, 4]
["a", "b"].concat("c", 1, "d") // → ["a", "b", "c", 1, "d"]
/*
* filter
*/
function isBigEnough(value) { return value >= 10; }
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // → filtered is [12, 130, 44]
/*
* map
*/
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt); // roots is now [1, 2, 3] (1*1=1, 2*2=4, 3*3=9), numbers is still [1, 4, 9]
/*
* reduce
*/
var total = [0, 1, 2, 3].reduce(function(a, b) { return a + b; }); // total == 6
/*
* forEach
*/
function logArrayElements(element, index, array) { console.log('a[' + index + '] = ' + element); }
[2, 5, , 9].forEach(logArrayElements); // → a[0] = 2 // → a[1] = 5 // → a[3] = 9
// Notice that index 2 is skipped since there is no item at that position in the array.
/*
* every & some
*/
function isBigEnough(element, index, array) { return element >= 10; }
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 5, 8, 130, 44].some(isBigEnough); // true
```
## Nodes
```javascript
/*
* Select children of an element with content
* given: table > tr > td + td
*/
var t = document.querySelector('#table');
var td = t.content.querySelectorAll("td"); // nodelist [td, td]
// note: without .content it would not be possible to select the childs.
/*
* clone nodes with importNode
* see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template for a good example
*/
var clone = document.importNode(externalNode, deep);
var tb = document.getElementsByTagName("tbody");
var clone = document.importNode(t.content, true); // import/clone the content of the table
tb[0].appendChild(clone); // append it to tbody
```
## Custom Constructors / Classes:
```javascript
// new Object(); is a predefined constructor by js that creates an empty object, we can create our own class constructors like so:
function Person(name,age) {
this.name = name;
this.age = age;
}
var bob = new Person("Bob Smith", 30); // creates an object/class Person with the keys/properties specified in our constructor
// here is where a constructor notation makes sence
function Dog (breed) {
this.breed = breed;
};
var buddy = new Dog("golden Retriever");
Dog.prototype.bark = function() { console.log("Woof"); }; // prototype adds that method to the constructor. Instead of buddy.bark = ...
buddy.bark();
var snoopy = new Dog("Beagle");
snoopy.bark(); // is also able to bark.
function Penguin(breed) {
this.breed = breed;
var priv = "Private Variable"; // a variable that is only accessible within the constructor
this.getPriv = function() { return priv; }; // to be able to access a private variable from outside
}
Penguin.prototype = new Dog(); // Penguins will inherit from Dog and also be able to bark. A Prototype Chain.
var penguin = new Penguin("penguin"); // create an instance of the Penguin class.
penguin.bark(); // Woof
/*
* defineProperty & hasOwnProperty
*/
Object.prototype.nonsense = "hi"; // hi will be an enumerable property, hence show up in any for .. in .. loop on any object. To prevent that use defineProperty
for (var name in map) console.log(name); // → pizza // → touched tree // → nonsense
delete Object.prototype.nonsense;
Object.defineProperty(Object.prototype, "hiddenNonsense", {enumerable: false, value: "hi"});
for (var name in map) console.log(name); // → pizza // → touched tree
console.log(map.hiddenNonsense); // → hi
// alternatively:
for (var name in map) {
if (map.hasOwnProperty(name)) {
// ... this is an own property
}
}
```
## Math:
```javascript
// returns the largest of 2 numbers
Math.max(10, 20) //-> 20
// returns the largest integer less than or equal to a given number
Math.floor( 45.95); //-> 45
/*
* Randoms
*/
// random Number between 0 and 1 but never 0 nor 1
Math.random() //-> i.e. 0.73452221
// *x sets the width and +y the range of the randomness
Math.floor(Math.random() * 5 + 1) // Random Number between 1-5
// Returns a random integer between min (included) and max (included)
// Using Math.round() will give you a non-uniform distribution!
function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/*
* .sqrt to calculate distances
*/
// Pythagorean theorem says that the square of the distance we are looking for is equal to the square of the x-coordinate plus the square of the y-coordinate thus **√(a2 + b2)** to calculate the distance to a point c:
Math.sqrt(a * a + b * b);
// or less chic: Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
```
## Loops:
```javascript
for(var i = 0; i < 6; i++){ }; // for a number of time
for(var p in obj){ } // for in iterates a specified variable p over all the enumerable properties of an object
while(true){ }; // while a condition is true
do{ }while(true); // does x while a condition is true (runs x at least once)
break; // terminate a loop, switch, or in conjunction with a label statement.
["a", "b", "c"].forEach(function(entry) { console.log(entry); }); //although move convenient, forEach is ~30% slower than a normal for loop
```
## Logical Operators
```javascript
if(true){ /* */ } else if (true){ /* */ } else { /* */ }
```
```javascript
switch(variable){ case 'option1': /* */ break; case 'option2': /* */ break; default: /* */ }
```
### Conditional Operator
```javascript
console.log(true ? 1 : 2); // → 1
console.log(false ? 1 : 2); // → 2
// The value before ? “picks” which of the other two values will come out. When true, the first value is chosen, and when false, the value on the right comes out.
```
## User Input
```javascript
var name = prompt("who're you?");
```
## JSON
```javascript
// JSON.stringify takes a JavaScript value and returns a JSON-encoded string
var string = JSON.stringify({name: "X", born: 1980});
console.log(string); // → {"name":"X","born":1980}
// JSON.parse takes such a string and converts it to the value it encodes
console.log(JSON.parse(string).born); // → 1980
```
## ES6
```javascript
/*
* Using glob variables in new objects
*/
var foo = 2;
var obj = { bar: 1, foo } //-> obj.bar = 1 -> obj.foo = 2
```
### Destructuring
```javascript
var foo = {
bar: 1,
baz: 2
};
var { bar, baz } = foo;
console.log(bar); //-> 1
console.log(baz); //-> 2 // instead of foo.bar / foo.baz
// also with arrays:
var array = [1, 2];
var [ a, b ] = array;
console.log(a,b) //-> 1 2
// very nice on functions:
// usually you would have an opts value but now
// you can destructure the incoming object directly in the function
// also note how we changed the name of weight to just w
function calcBmi({ weight: w, height, max, callback }){
var bmi = w / Math.pow(height, 2);
if(bmi > max) { console.log('sorry you are obese') }
if(callback) { callback(bmi) } // instead of if objs.callback
}
// by passing objects
calcBmi({ weight, height, max: 25 });
// you can now omit a data and it will just be passed as 'undefined', here we leave out max.
// also the order does not matter anymore!
calcBmi({ callback: function() {}, weight, height });
```
### Default Arguments
```javascript
function someThing(value = 12){
// stuff
}
```
### Template Strings
```javascript
var name = "will";
var thing = "party";
// old way
var greet = "hi, my name is" + name + "\n and I like to" + thing + "!";
// new way. Note the inline variables and how to break lines.
var greet = `hi, my name is ${name}
and I like to ${thing} !`;
```
### Scoping
```javascript
// let is the new var
// define block variables (only used within blocks)
if () { let b = 2; }
console.log(b); // undefined
// use const as default and change it to let only when you have to change the value
// const is also block scoped but unchangable
const a = 1;
a = 2; //-> error
```
### Classes
```javascript
// old:
function Parent() { /*constructor*/ }
Parent.prototype.foo = function() {}; // to add a function to the constructor
var parent = new Parent();
parent.foo();
// new
class Parent {
// in ES7 I could also add static properties here, like this:
age = 30;
constructor() {
}
foo() {
}
static bar() {
}
}
var parent = new Parent();
parent.foo();
parent.age; //-> 30
Parent.bar();
class Child extents Parent {
constructor() {
super() // will call the constructor of Parent
}
baz() {
}
}
var child = new Child();
child.baz(); // works
child.foo(); // works
```
### Arrow Functions
```javascript
// basics
// old
var foo = function(a, b) { return a + b; }
// new
var foo = (a, b) => { return a + b; }
// implicit returns (only on one liners):
do.something((a, b) => a + b);
// also without parenthesis when you only have one argument
do.something(a => a + 1);
[0,1,2].map(val => val+1); //-> [1,2,3]
// it also binds the this
var module = {
age: 30,
foo: function() {
setTimeout(() => { // automatically bind the previous this to the function
console.log(this.age); // still works
}, 100);
}
};
// note that it will overwrite i.e. jQuerys this value.
```
### Modules
```javascript
// old
module.exports.foo = function () {};
module.exports.bar = function () {};
// another file:
var myModule = require("myModule");
var foo = myModule.foo;
// new
export function foo() { };
export function bar() { };
export var x = 3;
import { foo, bar, x as test } from "myModule";
console.log(test) //-> 3
// or whole modules
export default {};
import myModule from "myModule";
```
### Generator Functions
```javascript
async function() {
var friends = await $.get("http://bla.com/friends")
console.log(friends);
} // returns one promise that is denible
```
## Tricks
### Get password combinations
```javascript
var passwords = function(chars, length){
var chars = chars.split("");
var index=[];
(function loop(base, i){
for(var k=0; k< chars.length; k++) {
if(i>1) loop(base+chars[k], i-1);
else index.push(base+chars[k]);
}
})("", length)
return index;
}
var possible = "0123456789";
var length = 4
var possibilities = passwords(possible, length);
```
Use them
```javascript
var length = possibilities.length;
(function loop(base, i){
if(i < 0) return;
let n = base[i]; i -= 1;
setTimeout(() => { return loop(base, i) });
})(possibilities, length);
```

View File

@@ -0,0 +1,41 @@
# 모듈
import와 export 키워드는 모듈에서만 사용할 수 있습니다.
## 모듈로 내보내기
모듈로 내보내려는 항목 앞에 export 키워드를 붙여 줍니다.
```javascript
export const PI = 3.141592;
export function hello() {
return "Hello";
};
```
또는, 모듈 파일의 맨 끝에 export 키워드로 내보낼 항목들을 나열합니다.
```javascript
const PI = 3.141592;
function hello() {
return "Hello";
};
export {
PI, hello
};
```
## 모듈 가져오기
```javascript
import { PI, hello } from "./mymodule.js";
```
## HTML에서 모듈 선언
```html
<script type="module" src="mymodule.js"></script>
```

View File

@@ -0,0 +1,94 @@
# 숫자
자바스크립트에서 모든 숫자는 8바이트 배정밀도 부동소수형으로 저장됩니다. 숫자에는 ```+Infinity```, ```-Infinity```, ```NaN``` 3개의 특수 값이 포함됩니다.
## Number
```javascript
Number.MAX_VALUE
Number.MIN_VALUE
Number.NaN
Number.NEGATIVE_INFINITY
Number.POSITIVE_INFINITY
Number.EPSILON
Number.MIN_SAFE_INTEGER
Number.MAX_SAFE_INTEGER
```
```javascript
Number.parseFloat()
Number.parseInt()
Number.isFinite()
Number.isInteger()
Number.isNaN()
Number.isSafeInteger()
```
```javascript
toExponential()
```
지수 표기법으로 나타낸 문자열을 반환합니다. 매개 변수에는 소수점 이하 자릿수를 전달합니다.
```javascript
toFixed()
```
고정 소수점 방식으로 표현된 문자열을 반환합니다. 매개 변수에는 소수점 이하 자릿수를 전달하며, 기본 값은 0입니다.
```javascript
toPrecision()
```
유효 자릿수에서 반올림한 문자열을 반환합니다. 매개 변수에는 유효자릿수를 전달합니다.
## Math
```javascript
Math.PI
```
```javascript
/* 절대값 */
Math.abs()
/* 삼각함수 */
Math.sin()
Math.cos()
Math.tan()
Math.asin()
Math.acos()
Math.atan()
Math.atan2()
Math.sinh()
Math.cosh()
Math.tanh()
Math.asinh()
Math.acosh()
Math.atanh()
/* 제곱근 */
Math.pow(a, n) // a의 n승
Math.sqrt(a) // 제곱근
Math.cbrt(a) // 세제곱근
/* 지수와 로그 */
Math.exp()
Math.expm1()
Math.log10()
Math.log1p()
Math.log2()
/* 올림과 내림 */
Math.floor()
Math.ceil()
Math.round()
Math.fround()
Math.trunc()
/* 최소, 최대 */
Math.min(a, ...)
Math.max(a, ...)
/* 랜덤 */
Math.random() // 0 ~ 1 사이의 값을 반환
/* 그 외 */
Math.hypot(a, ...)
Math.sign(a) // 어떤 수의 부호를 반환. 1, 0, -0, -1, NaN 중 하나를 반환.
Math.clz32(a) // 숫자를 32비트 이진 표현으로 변환 후 앞 쪽의 0의 갯수를 반환
Math.imul(a, b) // 두 숫자의 32비트 정수 곱셈. ECMAScript2015에서 추가되었습니다.
```

134
Writerside/topics/Object.md Normal file
View File

@@ -0,0 +1,134 @@
# 객체
```javascript
let obj = {}; // 또는
let obj = new Object();
obj.age = 14;
obj.name = "Charlie";
console.log(obj.name); // C언어의 구조체 스타일
console.log(obj['name']); // PHP의 연관 배열 스타일
```
## 객체의 프로퍼티 나열
```javascript
for (let key in obj) {
console.log(key);
}
for (let key of Object.keys(obj)) {
console.log(key);
}
for (let key of Object.getOwnPropertyNames(obj)) {
console.log(key);
}
```
## 생성자 함수
```javascript
function Person(name, age) {
this.name = name;
this.age = age;
}
let charlie = new Person("Charlie", 14);
```
### Object.create()
```javascript
let Point = {
x: 0,
y: 0,
toString: function () {
return "(" + this.x + ", " + this.y + ")";
}
};
let point1 = Object.create(Point);
console.log(point1.toString());
```
## 프로토타입을 통한 프로퍼티 정의
```prototype```을 통해서 프로퍼티를 추가하면, 하나의 인스턴스에만 추가된는 것이 아니라 해당 객체의 모든 인스턴스에 프로퍼티가 추가된다.
```javascript
Person.prototype.gender = "Male";
```
## 프로퍼티의 삭제
상속받지 않은 속성은 delete 연산자로 제거할 수 있습니다.
## 프로토타입 기반
자바나 C++과 같은 클래스 기반의 언어와는 달리 자바스크립트는 프로토타입 기반의 언어입니다. 프로토타입 기반 언어의 특징 상 클래스와 인스턴스의 구분이 모호해집니다.
```javascript
function Animal(name) {
this.name = name;
}
function Dog(name) { // Animal을 상속
Animal.call(this, name);
this.bark = function () {
console.log("멍멍");
};
}
Dog.prototype = Object.create(Animal.prototype);
let snoopy = new Dog("Snoopy");
console.log(snoopy.name);
snoopy.bark();
```
## 객체 속성의 해체
```javascript
let person = { name: "Charlie", age: 14 };
let { name, age } = person;
console.log(name);
console.log(age);
```
# 클래스
난해한 프로토타입 기반의 객체 대신 클래스 기반으로 클래스를 정의할 수도 있습니다.
```javascript
class Animal {
constructor(name) { // 생성자
this.name = name;
}
static someStaticMethod() { }
}
class Dog extends Animal { // 확장
constructor(name) {
super(name); // 부모 생성자 호출
}
}
let snoopy = new Dog("Snoopy");
console.log(snoopy.name);
```
# JSON
자바스크립트 객체와 문자열을 서로 변환할 수 있습니다.
```javascript
JSON.parse(str)
JSON.stringfy(obj)
```

View File

@@ -0,0 +1,96 @@
# 연산자
대부분 자바의 연산자와 같습니다.
## 비교 연산자
- 동등 (==)
서로 값이 참입니다.
- 부등 (!=)
서로 다르면 참입니다.
- 일치 (===)
서로 값이 같고 자료형도 같으면 참입니다.
- 불일치 (!==)
서로 값이 다르거나 자료형이 다르면 참입니다.
```javascript
3 == "3" // true
3 === "3" // false
```
## 숫자화 연산자 (+)
피연산자를 숫자로 변환합니다.
```
+"3" // 3
+true // 1.
```
## typeof
typeof 연산자를 사용하면 변수의 자료형을 알 수 있습니다.
```javascript
let a = function () { };
let b = "Hello";
let c = 1;
let d = [1, 2, 3];
let e = {};
let f;
let g = true;
let h = null;
console.log(typeof a); // function
console.log(typeof b); // string
console.log(typeof c); // number
console.log(typeof d); // object. 배열은 array일 것 같지만 object입니다.
console.log(typeof e); // object
console.log(typeof f); // undefined
console.log(typeof g); // boolean
console.log(typeof h); // object. null은 object입니다.
```
## instanceof
객체의 형태를 확인할 때 사용합니다.
```javascript
let a = new String("Hello");
let b = "Hello";
console.log((a instanceof String) ? "yes" : "no"); // yes
console.log((b instanceof String) ? "yes" : "no"); // no
```
## in
객체에 어떤 속성이 있는 경우에 true를 반환합니다.
```javascript
let array = ["a", "b", "c"];
console.log((1 in array) ? "yes" : "no"); // yes
console.log(("b" in array) ? "yes" : "no"); // no. 배열의 경우 인덱스를 사용해야 합니다.
console.log(("length" in array) ? "yes" : "no"); // yes. Array객체에 length메서드가 있으므로.
let obj = { a: "A", b: "B", c: "C" };
console.log(("b" in obj) ? "yes" : "no"); // yes
console.log(("PI" in Math) ? "yes" : "no"); // yes. Math객체에 PI가 있으므로
```
## void
void 연산자는 식을 평가하지만, 값을 반환하고 싶지 않을 때 사용합니다.
```html
<a href="javascript:void(0)">
<a href="javascript:void(document.form.submit())">
```

View File

@@ -0,0 +1,94 @@
# 프로미스
```javascript
let task1 = new Promise((resolve, reject) => {
try {
setTimeout(() => {
resolve({ message: "OK" });
}, 3000);
} catch (e) {
reject(e);
}
});
let i = 0;
const uid = setInterval(() => {
console.log(i);
i++;
}, 500);
task1.then((result) => {
console.log(result);
}).catch((reason) => {
console.error(reason);
}).finally(() => {
console.log("The End");
clearInterval(uid);
});
```
프로미스를 생성할 때에는 2 개의 콜백을 사용합니다. resolve는 작업이 성공했을 때 결과를 반환하고, reject는 작업이 실패했을 때 호출합니다.
비동기 작업이 성공하면 then이 호출되고 resolve에서 전달한 값을 받습니다. 실패한 경우에는 catch가 호출되고 reject에서 전달한 값을 받습니다. finally는 성공 또는 실패한 경우에 호출됩니다.
- Promise.resolve(val)
- Promise.reject(val)
```javascript
let task1 = Promise.resolve(100);
task1.then((result) => {
console.log(result);
});
let task2 = Promise.reject("BAD");
task2.catch((reason) => {
console.error(reason);
});
```
- Promise.all()
모든 프로미스가 완료된 이후에 결과가 배열로 전달됩니다.
- Promise.race()
처음으로 완료된 프로미스의 결과만 전달됩니다.
```javascript
let task1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 3000);
});
let task2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 2000);
});
let task3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 1000);
});
Promise.all([task1, task2, task3])
.then((result) => {
console.log(result); // [3, 2, 1]
});
Promise.race([task1, task2, task3])
.then((result) => {
console.log(result); // 1
});
```
## async / await
```javascript
async function myFunction(param) {
...
}
```
async 함수를 정의하기 위해 사용됩니다. async 함수에는 await식이 포함될 수 있습니다. await 문은 async 함수의 실행을 일시 중지하고 전달 된 Promise의 해결을 기다린 다음 async 함수의 실행을 다시 시작하고 완료후 값을 반환합니다. await 키워드는 async 함수에서만 유효하다는 것을 기억하십시오.

View File

@@ -0,0 +1,30 @@
# 정규표현식
```javascript
let regex = /[a-z0-9]*/;
let regex = new RegExp("[a-z0-9]*");
let regex = /[a-z0-9]*/g;
let regex = new RegExp("[a-z0-9]*", "g");
```
```javascript
exec(str) // 결과를 배열로 반환합니다. 일치하지 않으면 null을 반환합니다.
test(str) // 결과를 true 또는 false로 반환합니다.
```
```javascript
let regex = /(\w+)\s(\w+)/;
let result = regex.exec("stive jobs");
console.log(result);
/*
[
'stive jobs',
'stive',
'jobs',
index: 0,
input: 'stive jobs',
groups: undefined
]
*/
```

158
Writerside/topics/String.md Normal file
View File

@@ -0,0 +1,158 @@
# 문자열
## String
```javascript
let str = new String("Hello");
```
```javascript
charAt()
charCodeAt()
codePointAt()
indexOf()
lastIndexOf()
startsWith()
endsWith()
includes()
concat()
fromCharCode()
fromCodePoint()
split()
slice()
substring()
substr()
match(regexp)
replace(regexp)
search(regexp)
toLowerCae()
toUpperCase()
normalize()
repeat()
trim()
```
## 국제화; Intl
### DateTimeFormat
```javascript
const FORMAT = new Intl.DateTimeFormat("ko-KR", {
year: "numeric", month: "2-digit", day: "2-digit",
hour: "2-digit", minute: "2-digit", second: "2-digit",
timeZoneName: "long"
});
let now = new Date();
console.log(FORMAT.format(now));
```
#### 매개변수 옵션
- dateStyle
- full
- long
- medium
- short
- timeStyle
- full
- long
- medium
- short
- timeZone
"UTC", "Asia/Seoul", …
- hour12
12시간제 여부. true / false
- hourCycle
- h11
- h12
- h23
- h24
- weekday
- long
- short
- narrow
- era
- long
- short
- narrow
- year
- numeric
- 2-digit
- month
- numeric
- 2-digit
- long
- short
- narrow
- day
- numeric
- 2-digit
- hour
- numeric
- 2-digit
- minute
- numeric
- 2-digit
- second
- numeric
- 2-digit
- timeZoneName
- long
- short
### NumberFormat
```javascript
let PRICE_FORMAT = new Intl.NumberFormat("ko-KR", {
style: "currency", currency: "KRW",
minimumFractionDigits: 2
});
console.log(PRICE_FORMAT.format(1000));
```
#### 매개변수 옵션
- style
- decimal
- currency
- percent
- currency
"USD", "EUR", KRW", …
- currencyDisplay
- symbol
- code
- name
- useGrouping
천 단위 구분자. true / false
- minimumIntegerDigits
- minimumFractionDigits
- maximumFractionDigits
- minimumSignificantDigits
- maximumSignificantDigits

View File

@@ -0,0 +1,9 @@
# this
자바스크립트에서 this 키워드는 상식과 많이 다르게 작동합니다.
전역 컨텍스트에서의 this는 전역 객체(브라우저에서는 window 객체)를 가리킵니다.
일반적인 함수 컨텍스트에서는 전역 객체를 가리킵니다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

View File

@@ -0,0 +1,35 @@
# 웹소켓
```javascript
let websocket = new WebSocket("wss://echo.websocket.org/");
websocket.onopen = function (event) {
websocket.send("Hello");
};
websocket.onclose = function (event) {
console.log(event.code + ": " + event.reason);
};
websocket.onmessage = function (event) {
console.log(event.data);
};
websocket.onerror = function (event) {
};
```
- send()
서버에 데이터 전송. String, Blob, ArrayBuffer를 보낼 수 있습니다.
- close()
연결을 닫습니다.
- onopen
- onclose
- onerror
- onmessage