Cheat sheet
ทุกคำสั่งและตารางที่ต้องจำของวิชานี้ รวมไว้หน้าเดียว
HTML
<!DOCTYPE html> HTML5 doctype <meta charset="UTF-8"> ชุดอักขระ <meta name="viewport" content="width=device-width, initial-scale=1"> Empty element : br img hr meta input link area Semantic HTML5: header nav main section article aside address footer div = block · span = inline form: action="/submit" method="post|get" input: text password email number date color radio checkbox file hidden submit reset button attribute: placeholder required disabled(ไม่ส่งค่า) readonly(ส่งค่า) checked name
CSS
.class #id tag * selector หลัก
.container > p child (ลูกชั้นเดียว)
.container p descendant (ทุกชั้น)
p + span adjacent sibling
span[title='x'] attribute selector
:hover :link :visited :not() pseudo-class (ไม่สร้าง element)
::before ::after pseudo-element (สร้าง element)
ul li:first-child
@keyframes ชื่อ { from{} to{} } + animation-name / animation-duration
timing: linear ease ease-in ease-out ease-in-out
:root { --blue: #1e90ff; } → color: var(--blue);
SCSS: $ตัวแปร · nesting · @mixin + @include
Git
Working Tree → git add → Staging Area → git commit → Local Repo → git push → Remote git --version git init git status git add file.html git add . git add *.html git commit -m "msg" git push git pull git remote -v git remote add origin <url> git reset --option <commit_id> Merge conflict: pull → แก้เอง → git add → git commit → git push
JS พื้นฐาน
var = ทะลุ block (ไม่ทะลุ function) let = จำกัดใน block const = ค่าคงที่
typeof x ชนิด: number string boolean null undefined NaN
parseInt("10") parseFloat("10") A + "" A.toString()
== เทียบค่า (10 == "10" → true)
=== เทียบค่าและชนิด (10 === "10" → false)
falsy: "" 0 -0 null undefined NaN
hoisting: var → undefined, let/const → ReferenceError
"use strict"; บังคับประกาศตัวแปร
for / while / do-while / break / continue
for-in → key ของ object
for-of → value ของสิ่งที่มี index (array, string, set)
forEach → วนสมาชิก array
arrow: let f = (p) => p; default param: function f(x, y = 2)
template: `text ${var}` (back tick เท่านั้น)
spread: [...arr] rest: function f(...args)
JSON.stringify(obj) → string JSON.parse(str) → object
JSON เก็บ function ไม่ได้ และ key ต้องมีเครื่องหมายคำพูด
setTimeout(fn, ms) / clearTimeout(id)
setInterval(fn, ms) / clearInterval(id)
Math.floor(Math.random() * 10) → 0-9
Array
| เมธอด | ทำอะไร | เปลี่ยน array เดิมไหม |
|---|---|---|
push / pop | เพิ่ม / เอาออก ที่ท้าย | เปลี่ยน |
unshift / shift | เพิ่ม / เอาออก ที่หัว | เปลี่ยน |
splice(i, n) | ลบ n ตัวจากตำแหน่ง i (แทรกค่าใหม่ได้) | เปลี่ยน |
slice(a, b) | ตัดช่วงออกมาเป็น array ใหม่ | ไม่เปลี่ยน |
join / concat | รวมเป็นสตริง / รวม 2 array | ไม่เปลี่ยน |
indexOf / find / findIndex | ค้นหา (index / ค่า / index) | ไม่เปลี่ยน |
map | แปลงค่าทุกตัว — fn ต้อง return | ไม่เปลี่ยน |
filter | คัดกรอง — fn เป็น เงื่อนไข | ไม่เปลี่ยน |
reduce((prev,curr)=>{}, init) | ยุบเหลือค่าเดียว | ไม่เปลี่ยน |
sort((a,b)=>a-b) | เรียง — ไม่ใส่ fn จะเรียงแบบ string | เปลี่ยน |
OOP & Module
class Car { constructor(name){ this.name = name; } age(x){ return x - this.year; } }
new Car("Ford", 2014)
class B extends A { constructor(){ super(); } }
#field → private (encapsulation)
JS ไม่มี method overloading → ใช้ arguments.length
JS ไม่มี generic <T> → ใช้ TypeScript
prototype: Car1.__proto__ === Car.prototype → true
เพิ่ม property ให้ chain: CarFunc.prototype.color = "green"
เพิ่มแบบไม่ chain: CarFunc.color = "green" → ลูกได้ undefined
บนสุดของ chain: Object.prototype
export { name, age }; → import { name } from './x.js'
export default person; → import person from './x.js'
<script type="module">
Async
ฟังก์ชัน async: setTimeout, setInterval, AJAX request
new Promise((resolve, reject) => { ... })
.then(result => {}) .catch(error => {})
สถานะ: pending → fulfilled / rejected
async function f(){ await g(); } await ใช้ได้เฉพาะใน async function
Promise.any([p1, p2]) เอาตัวที่ resolve เร็วสุด
XMLHttpRequest readyState:
0 UNSENT · 1 OPENED · 2 HEADERS_RECEIVED · 3 LOADING · 4 DONE
เช็ค: readyState == 4 && status == 200
xhttp.open("GET", url, true) true = asynchronous
DOM
getElementById('x') → 1 element
getElementsByClassName('c') → collection ต้องใส่ [0]
getElementsByTagName('div') → collection
querySelector('.c') → ตัวแรกที่ตรง CSS selector
querySelectorAll('.c') → ทุกตัว
innerHTML set = สร้าง element จริง (เสี่ยง XSS)
textContent set = ข้อความล้วน (ปลอดภัยกว่า)
setAttribute / getAttribute / removeAttribute / hasAttribute
classList.add / classList.remove
createElement → appendChild (ท้าย) / prepend (หน้า)
remove() / parent.removeChild(child)
cloneNode(true) = เอาลูกมาด้วย, false = เฉพาะตัวเอง
ผูก event 3 วิธี: onclick ใน HTML · element.onclick · addEventListener (ดีสุด)
event: click mouseover mouseout keydown keyup submit change focus blur
addEventListener(type, fn, false) = bubbling (ค่าปริยาย, ล่าง→บน)
addEventListener(type, fn, true) = capturing (บน→ล่าง)
event.target = ตัวที่ถูกคลิกจริง · event.currentTarget = ตัวที่ผูก handler
event.stopPropagation() = หยุดไม่ให้วิ่งต่อ
HTTP & API
HTTP/1.0 เปิด-ปิด connection ทุกรอบ
HTTP/1.1 persistent (เปิดครั้งเดียว) / pipelining (ส่ง req ติดกัน)
HTTP/2.0 หลาย req ใน connection เดียว res ไม่ต้องเรียงลำดับ
Header = metadata (Content-Type, method) · Body = ข้อมูลจริง
GET อ่าน · POST เพิ่ม · PUT แก้ทั้งชิ้น · PATCH แก้บางส่วน · DELETE ลบ
HEAD CONNECT OPTIONS TRACE
200 OK · 400 Bad Request · 401 Unauthorized · 403 Forbidden
404 Not Found · 500 Internal Server Error · 504 Gateway Timeout
fetch(url).then(r => r.json()).then(d => {}).catch(e => {})
fetch(url, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(x) })
รูปแบบแปลง: .text() .json() .blob() .formData()
axios: npm install axios → response.data ได้เลย
SOAP = XML · REST = JSON (นิยมสุด) · GraphQL = เลือก field เองได้
WebSocket = สองทางต่อเนื่อง · Webhook = server ยิงกลับมาเมื่อมีเหตุการณ์
Node & Express
npm init · npm install express · npm install -g typescript · npx
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(3000);
req.params.id (จาก /data/:id) · req.query.x (จาก ?x=1) · req.body
MariaDB : pool.getConnection() → conn.query("... ?", [value]) → conn.end()
MongoDB : database > collection > document (BSON) · mongoose = ODM
ORM Prisma: model → npx prisma db push → findMany/create/update/delete
include = Eager Loading · select = Lazy Loading
TypeScript: tsc app.ts → app.js · tsc --init → tsconfig.json
rootDir / outDir / include
กับดักข้อสอบ
- JavaScript ไม่ใช่ Java — คนละภาษา สร้างโดย Brendan Eich ปี 1994
- == กับ === —
10 == "10"เป็น true แต่10 === "10"เป็น false - var ทะลุ block แต่ไม่ทะลุ function
- hoisting — var ได้ undefined ส่วน let/const เกิด ReferenceError
- for-in ได้ key / for-of ได้ value
- sort() ไม่ใส่ฟังก์ชัน = เรียงแบบ string ([2,10,1] → [1,10,2])
- map ต้อง return / filter ต้องเป็นเงื่อนไข
- callback ส่งชื่อฟังก์ชันเปล่า ๆ ห้ามใส่วงเล็บ
- เพิ่ม property ให้ chain ต้องผ่าน .prototype
- await ใช้ได้เฉพาะใน async function
- XMLHttpRequest ต้องเช็ค readyState 4 และ status 200
- getElementsBy... ได้ collection ต้องใส่ index
- innerHTML สร้าง element จริง / textContent เป็นข้อความล้วน
- addEventListener ค่าปริยายเป็น bubbling (ล่างขึ้นบน) และลำดับไม่ขึ้นกับบรรทัดที่เขียนโค้ด
- ใช้ POST แทน DELETE ได้แต่ไม่เป็นมาตรฐาน
- query ต้องใช้ placeholder ? กัน SQL Injection
- require ใช้ฝั่ง server ส่วน import เป็น ECMAScript module