JavaScript 開發中,常會遇到路徑處理、參數取得、陣列操作、Cookie、計時器與事件等基礎題。以下整理常見用法,方便查閱。
絕對路徑通常以 / 開頭,代表網站根目錄;相對路徑則是相對於目前頁面的位置。若要取得根目錄,可以透過 window.location 組出路徑前段。
function GetRootPath() {
var strFullPath = window.document.location.href;
var strPath = window.document.location.pathname;
var pos = strFullPath.indexOf(strPath);
var prePath = strFullPath.substring(0, pos);
var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
return prePath + postPath;
}取得網址參數時,現代瀏覽器可直接使用 URLSearchParams:
var params = new URLSearchParams(window.location.search);
var a = params.get("a");Math.round 可四捨五入,Math.random 可取得 0 到 1 之間的隨機數,isNaN 可判斷是否為非數字,Number、parseFloat、parseInt 與 String 則常用於型別轉換。
concat 可合併陣列並產生新陣列,join 可把陣列轉成字串。正則表達式常用 test 方法判斷是否符合規則:
var patt1 = new RegExp("e");
console.log(patt1.test("The best things in life are free"));onload、onUnload 用於頁面載入與卸載;onFocus、onBlur、onChange 常用於表單驗證;onSubmit 則可在表單送出前進行整體檢查。
function setCookie(name, value, days) {
var date = new Date();
date.setDate(date.getDate() + days);
document.cookie = name + "=" + escape(value) + ";expires=" + date.toUTCString();
}setTimeout 可延遲執行,clearTimeout 可停止計時。window.open 可開啟新視窗,window.location.href 則可導向同一視窗。
物件可以透過 new Object、JSON 字面量、建構函式或 prototype 建立。實際開發時,可依需求選擇適合的模式。