有些 JavaScript 寫法因為夠巧妙而廣為流傳,有些則是歷史的產物。本文把常見的技巧逐一檢視,說明原理,並標註哪些到今天仍然值得用、哪些已經該淘汰。
new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) )
出自 jQuery 的 Sizzle 選擇器引擎。把既有正則的 .source 取出來拼接,可以避免自己手寫時搞錯跳脫——正則字面值裡的 \\ 在 new RegExp 的字串中要寫成 \\\\,一層層轉義非常容易出錯。用 .source 就沒這個問題。
評價:仍然值得學。 動態組合正則時,優先考慮 RegExp.prototype.source 與 named capture group。
function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
}
原理是巧妙但繞:除以 10 的次方後用 toFixed 補到指定位數,小數點會往前位移,再用 substr(2) 砍掉「整數.」這兩個字元。
現代寫法(清楚得多):
String(num).padStart(length, "0"); // 7 → "007"
new Intl.NumberFormat("zh-TW", { minimumIntegerDigits: 3 }).format(7);
Math.max.apply(Math, [1, 2, 3]) // 3 Math.min.apply(Math, [1, 2, 3]) // 1
因為 Math.max 不接受陣列,只能透過 apply 把陣列展開成參數。
現代寫法:
Math.max(...[1, 2, 3]); Math.max(...arr);
但要注意:陣列長度過大(通常超過十萬筆)時,展開成參數會觸發 Maximum call stack size exceeded。大量資料請用 reduce:
arr.reduce(function (max, n) { return Math.max(max, n); }, -Infinity);
Math.random().toString(16).substring(2); // 8 位 Math.random().toString(36).substring(2); // 更長
原理是把小數用其他進位表示,0.xxxxx 會變成 "0.abc123",砍掉前兩個字元就是亂數。
注意:這不是加密安全的隨機數。 若用於 token、Session ID、忘記密碼連結,必須改用:
crypto.randomUUID(); // UUID v4 crypto.getRandomValues(new Uint32Array(1))[0].toString(36);
var timeStamp = Number(new Date); // 比 new Date().getTime() 簡潔
更好的寫法: Date.now(),這是專門的靜態方法,不必建立物件。
var result = '3.1415926' | 0; // 3
用位元或運算 | 0 無條件捨去,因為位元運算會把運算元轉成 32 位元整數。
但這有陷阱:它只適用於 32 位元範圍內的數字,超過 2147483647 會溢出成負數。請改用:
Math.trunc('3.1415926'); // 3,語意明確且無範圍限制
parseInt(str, 10); // 若只想取整數部分
function format(format) {
if (!FB.String.format._formatRE) {
FB.String.format._formatRE = /(\{[^\}^\{]+\})/g;
}
var values = arguments;
return format.replace(FB.String.format._formatRE, function (str, m) {
var index = parseInt(m.substr(1), 10),
value = values[index + 1];
if (value === null || value === undefined) return '';
return value.toString();
});
}
format('{0}.facebook.com/{1}', 'www', 'login.php');
// → www.facebook.com/login.php
現代寫法: ES6 的模板字面值直接解決:
const tpl = `https://${host}/${path}`;
若模板是執行期才拿到的字串(例如放在資料庫或 i18n 檔中),則可寫成:
function format(str, params) {
return str.replace(/\{(\w+)\}/g, function (m, key) {
return params[key] != null ? params[key] : "";
});
}
format("{host}/{path}", { host: "www", path: "login.php" });
var foo = 1, bar = 2; foo = [bar, bar = foo][0];
利用陣列字面值的求值順序:先取 bar 放進陣列,再執行 bar = foo。
現代寫法:
[foo, bar] = [bar, foo]; // 解構賦值,意圖一目了然
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{(\d+)\}/g, function (full, idx) {
return args[idx];
});
}
'Hello {0}, How{1}'.format('Bob', ' you doin');
強烈不建議擴充原生原型。 這會污染全域,與其他程式庫衝突,且讓程式碼行為難以預測。改成獨立函數即可,功能完全相同。
(function () {
// do something
})();
最簡單也最實用的技巧,奠定了 JavaScript 模組化的基礎——在 ES Module 出現之前,這是唯一能建立私有作用域的方式。
今日狀態: 在瀏覽器中使用 <script type="module">,或在 Node.js 中使用 import/require,作用域自動隔離,不需要再手寫 IIFE。但在 CommonJS 環境中仍有其價值。
var some = con1 ? val1 : con2 ? val2 : con3 ? val3 : defaultVal;
能寫,但不建議。三層以上就難以閱讀,除錯時也難以中斷點。改用 if/else if 或查表:
const map = { a: val1, b: val2, c: val3 };
const some = map[con] ?? defaultVal;
出自 CKEditor 的設計:用一個陣列存放函數,對外只暴露 id,讓閉包內的函數能被全域呼叫而不污染全域命名空間。
(function () {
var fns = [];
function toArray(arrayLike, index) {
return Array.prototype.slice.call(arrayLike, index || 0);
}
window.Util = {
'addFunction': function (fn, scope) {
return fns.push(function () {
return fn.apply(scope || window, arguments);
}) - 1;
},
'removeFunction': function (index) { fns[index] = null; },
'callFunction': function (index) {
var fn = fns[index];
return fn && fn.apply(window, toArray(arguments, 1));
}
};
})();
var fnId = Util.addFunction(function (msg) { alert(msg); });
Util.callFunction(fnId, 'Hello, World');
這個模式在今天仍有價值,特別是需要把「HTML 內嵌事件(如 onclick="fnId(3)")」與實際函數分離時。不過更現代的替代是事件委派:用 data-* 屬性存放參數,在容器上綁一個監聽器,完全不需要全域函數。
console.log(true && something); // → something console.log(false && something); // → false console.log(true || something); // → true console.log(false || something); // → something
&& 取「第一個假值」,|| 取「第一個真值」。常見用法是設定預設值:
var name = user.name || "匿名";
但這裡有經典陷阱:若 user.name 是 0、"" 或 false,都會被誤判成「沒有值」而套用預設。請改用空值定併:
var name = user.name ?? "匿名"; // 只在 null / undefined 時才用預設 var count = options.retry ?? 3; // 0 是合法值,不會被覆蓋
| 0 取整 → 改用 Math.trunc()(範圍限制)|| 設預設值 → 改用 ??(誤判假值)String.prototype → 改用獨立函數或 ES ModuleMath.random() 做 token → 改用 crypto API仍然值得保留的:.source 組裝正則、IIFE 的立即執行概念、短路運算的邏輯思維、以及函數註冊表的設計思路。這些技巧的價值在於理解 JavaScript 的求值規則,而非照抄語法。