在框架與 npm 套件還不盛行的年代,每個團隊都會攢一份自己的小工具庫,做法通常就是往各個內建原型上擴充方法。這份就是那類合集,涵蓋陣列檢索、日期格式化與運算、字串處理三大塊。
/**
* 檢索陣列元素
* @param {o} 被檢索的元素值
* @returns 元素索引,找不到回傳 -1
*/
Array.prototype.contains = function(o) {
var index = -1;
for (var i = 0; i < this.length; i++){
if (this[i] == o){ index = i; break; }
}
return index;
}
這是全庫最實用的一段。支援的格式符號:
YYYY / yyyy / YY / yy:年MM / M:月W / w:星期dd / DD / d / D:日hh / HH / h / H:時mm / m:分ss / SS / s / S:秒Date.prototype.format = function(formatStr){
var str = formatStr;
var Week = ['日','一','二','三','四','五','六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9
? (this.getYear() % 100).toString()
: '0' + (this.getYear() % 100));
str = str.replace(/MM/, (this.getMonth() + 1) > 9
? (this.getMonth() + 1).toString()
: '0' + (this.getMonth() + 1));
str = str.replace(/M/g, this.getMonth()); // 註:此處應為 +1
str = str.replace(/w|W/g, Week[this.getDay()]);
str = str.replace(/dd|DD/, this.getDate() > 9
? this.getDate().toString() : '0' + this.getDate());
str = str.replace(/d|D/g, this.getDate());
str = str.replace(/hh|HH/, this.getHours() > 9
? this.getHours().toString() : '0' + this.getHours());
str = str.replace(/h|H/g, this.getHours());
str = str.replace(/mm/, this.getMinutes() > 9
? this.getMinutes().toString() : '0' + this.getMinutes());
str = str.replace(/m/g, this.getMinutes());
str = str.replace(/ss|SS/, this.getSeconds() > 9
? this.getSeconds().toString() : '0' + this.getSeconds());
str = str.replace(/s|S/g, this.getSeconds());
return str;
}
這段程式碼有兩個已知瑕疵值得注意:getMonth() 回傳的是 0 起算的月份,所以單獨的 M 輸出會少一個月;而「先替換長格式、再替換短格式」的策略在遇到 YYYY-MM-dd 這種組合時,若短格式替換用了 /g,有機會把已替換的數字中的字母再次替換掉。這類問題正是後來 Intl.DateTimeFormat 與 date-fns 等庫要解決的。
庫中另外提供了三個方法:
dateDiff(strInterval, dtEnd):計算與另一個日期的差值,strInterval 支援 s / n / h / d / w / m / y(秒、分、時、日、週、月、年),內部靠「兩個 Date 相減得到毫秒數」再換算。dateAdd(strInterval, Number):加上或減去一段時間,回傳新的 Date。實作上多數分支用 Date.parse(dtTmp) + 毫秒數,而 m(月)與 y(年)因為每月天數不一,改用 new Date(year, month + n, ...) 的建構子形式。datePart(interval):取出年、月、日、週、時、分、秒等單一成分。此外還有 toArray()(拆成 [年,月,日,時,分,秒])、daysOfMonth()(本月天數)、isLeapYear()(閏年判斷,標準的「四年一閏、百年不閏、四百年再閏」規則),以及兩個全域函式 daysDiff() 與 dateAdd()。
其中 dateAdd 的全域版本用 eval("var prmDate = new Date(" + prmDate.join(",") + ")") 把字串轉日期——這種用法應該避免,改用 split(/\D/) 後直接呼叫 new Date(y, m-1, d) 即可,不必動用 eval。
/** 取得字串長度(中文字元算 2) */
String.prototype.len = function() {
var arr = this.match(/[^\x00-\xff]/ig);
return this.length + (arr == null ? 0 : arr.length);
};
/** 左取 / 右取指定個數,mode 為真時會把全形字元按 2 位計算 */
String.prototype.left = function(num, mode) {
if(!/\d+/.test(num)) return this;
var str = this.substr(0, num);
if(!mode) return str;
var n = str.len() - str.length;
num = num - parseInt(n / 2);
return this.substr(0, num);
};
String.prototype.right = function(num, mode) { /* 同上,改取右側 */ };
/** 去除兩端 / 左 / 右空白 */
String.prototype.trim = function(){ return this.replace(/(^\s*)|(\s*$)/g, ""); };
String.prototype.lTrim = function(){ return this.replace(/(^\s*)/g, ""); };
String.prototype.rTrim = function(){ return this.replace(/(\s*$)/g, ""); };
/** 計算子字串出現次數,mode 為真時忽略大小寫 */
String.prototype.matchCount = function(str, mode) {
return eval("this.match(/(" + str + ")/g" + (mode ? "i" : "") + ").length");
};
/** 字串轉日期 */
String.prototype.toDate = function() {
var converted = Date.parse(this);
var myDate = new Date(converted);
if (isNaN(myDate)) {
var arys = this.split('-');
myDate = new Date(arys[0], --arys[1], arys[2]);
}
return myDate;
};
len() 的「中文算兩個字元」在早年做輸入長度限制時很常用(因為資料庫欄位以位元組計),而 left / right 的 mode 參數就是為了讓「取 10 個字」在遇到中英混排時不會切壞。這個需求今天仍然存在,但標準解法是 Intl.Segmenter 或 Array.from(str) 配合 TextEncoder 來算位元組。
這份程式碼裡有幾個典型的時代印記:eval 用來組字串與正則、往內建原型上直接擴充、substr 這種已廢棄的 API、以及自己實作 trim 與日期格式化。這些在今天都有更好的答案:
Intl.DateTimeFormat、Temporal API,或 date-fns / dayjs。trim、includes、padStart、模板字面量。indexOf、includes、findIndex。但讀一遍仍有價值:它示範了「用原型擴充把語言補齊」這個思路的完整面貌,也讓你認得出老專案裡那些沒頭沒尾的 arr.contains(x)、date.format('yyyy-MM-dd') 是從哪裡冒出來的。