萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實用原生 API 精選:解析、位運算、日期、編碼、類型檢測、繼承實戰技巧

JavaScript 標準庫藏著許多「隱藏寶石」,善用它們能寫出更簡潔、高效、專業的程式碼。本文精選 10 類高頻實用原生 API 與技巧,涵蓋字串解析、位運算、日期格式化、URL 編碼、數字格式化、類型檢測、原型繼承等,附實戰範例與現代替代方案。

1. 解析「類物件」字串:eval 的正確姿勢

當字串長得像物件但不是標準 JSON(如鍵名無引號),`JSON.parse` 會報錯,`eval` 可解析但需安全包裹:

const str = "{a:1,b:2}"; // 非標準 JSON
const obj = eval("(" + str + ")"); // {a: 1, b: 2}

// 安全包裝函式
function safeParse(str) {
    try {
        // 簡單驗證:只允許字母、數字、冒號、逗號、大括號、引號
        if (!/^[\s\{a-zA-Z0-9_:,"'\-]*$/.test(str)) throw new Error('Invalid chars');
        return eval("(" + str + ")");
    } catch (e) {
        console.warn('Parse failed:', e);
        return null;
    }
}
⚠️ 警告:`eval` 執行任意程式碼,**絕對不可用於不可信輸入**(用戶輸入、外部 API 回傳)。可信環境下可用,否則請用正規解析器。

2. 位運算技巧:& (AND) 與 ^ (XOR)

判斷 2 的 n 次方

function isPowerOfTwo(n) {
    return n > 0 && (n & (n - 1)) === 0;
}
isPowerOfTwo(4);  // true (100 & 011 = 0)
isPowerOfTwo(5);  // false (101 & 100 = 100 !== 0)
isPowerOfTwo(1);  // true (2^0)

原理:2 的冪二進位只有單一 1,減 1 後所有低位變 1,相與必為 0。

不借第三變數交換兩數 (XOR Swap)

let a = 4, b = 3;
a = a ^ b; // a=7 (111)
b = a ^ b; // b=4 (111^011=100)
a = a ^ b; // a=3 (111^100=011)
console.log(a, b); // 3, 4

// 現代解構賦值更優雅:[a, b] = [b, a];

3. 日期格式化三步走

const now = new Date();

// 1. 取得本地化日期時間字串
const dateStr = now.toLocaleDateString(); // "2025/1/13"
const timeStr = now.toLocaleTimeString(); // "上午9:04:10"

// 2. 統一分隔符為連字號
const formatted = (dateStr + ' ' + timeStr.slice(2)).replace(/\//g, '-'); 
// "2025-1-13 9:04:10"

// 3. 字串轉回 Date 物件
const parsed = new Date("2025-1-13 9:04:10"); // 自動解析

// 4. 取得 Unix 時間戳 (毫秒)
const timestamp = now.valueOf(); // 或 +now, now.getTime()
console.log(timestamp); // 1736730250123

4. 一元加號 + 快速轉數字

const str = "23";
console.log(typeof str);     // "string"
console.log(typeof +str);    // "number" (一元加號轉型)
console.log(+new Date());    // 當前時間戳 (數字)
console.log(+true);          // 1
console.log(+false);         // 0
console.log(+null);          // 0
console.log(+undefined);     // NaN

5. URL 編碼/解碼:encodeURIComponent / decodeURIComponent

const url = 'https://example.com/search?q=中文&page=1';

// 編碼單一參數值 (最常用)
const encoded = encodeURIComponent(url); 
// "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3D%E4%B8%AD%E6%96%87%26page%3D1"

// 解碼
console.log(decodeURIComponent(encoded)); // 原始字串

// 構建查詢字串現代寫法
const params = new URLSearchParams({ q: '中文', page: 1 });
console.log(params.toString()); // "q=%E4%B8%AD%E6%96%87&page=1"

6. 數字格式化:toFixed / toPrecision / toLocaleString

const num = 12345.6789;

num.toFixed(0);     // "12346" (四捨五入整數)
num.toFixed(2);     // "12345.68" (保留 2 位小數)
num.toFixed(6);     // "12345.678900" (補零)

num.toPrecision(4); // "1.235e+4" (有效位數 4 位,科學記號)
num.toPrecision(7); // "12345.68"

num.toLocaleString();       // "12,345.679" (依地區設定千分位)
num.toLocaleString('zh-TW', { style: 'currency', currency: 'TWD' }); 
// "NT$12,346" (貨幣格式化)

7. 精準類型檢測:Object.prototype.toString.call

`typeof` 對物件類型無法區分,`instanceof` 受原型鏈污染。最可靠的是 `Object.prototype.toString.call()`:

const toString = Object.prototype.toString;

toString.call(123);           // "[object Number]"
toString.call('str');         // "[object String]"
toString.call(true);          // "[object Boolean]"
toString.call([1,2,3]);       // "[object Array]"
toString.call({a:1});         // "[object Object]"
toString.call(new Date());    // "[object Date]"
toString.call(/regex/);       // "[object RegExp]"
toString.call(null);          // "[object Null]"
toString.call(undefined);     // "[object Undefined]"
toString.call(function(){});  // "[object Function]"

// 封裝通用類型判斷
function getType(value) {
    return toString.call(value).slice(8, -1).toLowerCase(); 
    // "number", "string", "array", "date", "regexp", "null", "undefined"...
}

getType([]);        // "array"
getType(new Date()); // "date"

8. 原型繼承:Object.create 現代模式

// 父類別
const Animal = {
    init(name) { this.name = name; },
    speak() { console.log(this.name + ' makes a sound'); }
};

// 子類別繼承
const Dog = Object.create(Animal);
Dog.init = function(name, breed) {
    Animal.init.call(this, name); // 呼叫父初始化
    this.breed = breed;
};
Dog.speak = function() {
    console.log(this.name + ' barks! (' + this.breed + ')');
};

// 實例化
const dog = Object.create(Dog);
dog.init('旺財', '柴犬');
dog.speak(); // "旺財 barks! (柴犬)"

// ES6 class 語法糖 (底層仍是原型繼承)
class AnimalES6 {
    constructor(name) { this.name = name; }
    speak() { console.log(this.name + ' makes a sound'); }
}
class DogES6 extends AnimalES6 {
    constructor(name, breed) {
        super(name);
        this.breed = breed;
    }
    speak() { console.log(this.name + ' barks! (' + this.breed + ')'); }
}

9. 陣列/物件常用新方法 (ES2015+)

// 陣列
[1,2,3].includes(2);        // true
[1,2,3].find(x => x > 1);   // 2
[1,2,3].filter(x => x > 1); // [2,3]
[1,2,3].map(x => x * 2);    // [2,4,6]
[1,2,3].reduce((a,b)=>a+b); // 6
[...new Set([1,2,2,3])];     // [1,2,3] 去重
[1,2,[3,4]].flat();         // [1,2,3,4]

// 物件
Object.keys({a:1,b:2});     // ["a","b"]
Object.values({a:1,b:2});   // [1,2]
Object.entries({a:1,b:2});  // [["a",1],["b",2]]
Object.assign({}, {a:1}, {b:2}); // {a:1,b:2} 合併
{a:1, ...{b:2}};            // {a:1,b:2} 展開運算子

10. 實用單行技巧集

// 隨機整數 [min, max]
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

// 深拷貝 (簡易版,不含函式/循環引用)
const deepClone = obj => JSON.parse(JSON.stringify(obj));

// 扁平化陣列
const flatten = arr => arr.flat(Infinity);

// 去抖動
const debounce = (fn, ms) => {
    let timer;
    return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); };
};

// 節流
const throttle = (fn, ms) => {
    let last = 0;
    return (...args) => { const now = Date.now(); if (now - last >= ms) { last = now; fn(...args); } };
};

// 當前時間戳秒數
const nowSec = () => Math.floor(Date.now() / 1000);

結語

掌握原生 API 能減少對第三方庫的依賴、提升執行效能、加深語言理解。建議建立個人常用片段庫,並在 Code Review 時主動替換冗餘邏輯為標準 API。

copyright © 萬盛學電腦網 all rights reserved