Skip to content

JavaScript

Useful

位數逗號分隔
console.log(n.toLocaleString());
parseInt('') => NaN
'' === '' => true
NaN === NaN => false

// regex: Capturing Group
/\[(.*)\]__(.*)__([0-9]*)/.exec('[10]__foo__234')
// => [ "[10]__fofo__234", "10", "fofo", "234" ]
Capturing group: (...) - JavaScript | MDN

Vanilla

ready (ignore old IE8, IE9)
document.addEventListener('DOMContentLoaded', function () {
  // do something here ...
}, false);
如果要等所有 external resource (css, images) loaded
window.addEventListener('load', function () {
  // do something here ...
}, false);

Form

Patterns

IIFE

The many ways to write an Immediately Invoked Function Expression (IIFE) in JavaScript | Go Make Things

(function () {
    // Code goes here...
})();

Revealing Module Pattern

The vanilla JS revealing module pattern | Go Make Things

a collection of helper functions

let calculator = (function () {

    // ...

    /**
     * Divide two or more numbers
     * @param {...Number} nums The numbers to divide
     */
    function divide (...nums) {
        // ...
    }

    return {add, subtract, multiply, divide};

})();

Constructor Pattern

The vanilla JS constructor pattern | Go Make Things

like jQuery

Class Pattern

The vanilla JS Class pattern | Go Make Things

s- static

  • private

console

Let's be fancy with a console signature - DEV Community

var consoleSignatureStyle = "font-size: 16px;" +
  "background: linear-gradient(to right, #e66465, #9198e5);" +
  "color: white;" +
  "text-align: center;" +
  "padding: 10px 15px;" +
  "width: 100%;" +
  "border-radius: 20px;";

var consoleSignatureText = "%cDon't steal my cookies! 🍪";

console.log(consoleSignatureText, consoleSignatureStyle);

async

Tools

NProgress: slim progress bars in JavaScript

Package manager

Yarn

不建議用npm install -g yarn,Node.js 14.9/16.9後就有corepack enable的指令。enable後,就有yarn的指令可以用了

corepack enable

Svelte

原本的 npm create svelte@latest my-app 會裝一堆東西,包括sveltekit,用vite安裝純Svelte就好

只要client-side

npm init vite myapp
選單 (JavaScript, TypeScript)

cd myapp
npm install
npm run dev