整理前端高頻使用的原生 JS 工具函式,涵蓋型別判斷、空值檢查、字串位元組長度計算,無外部依賴,可直接納入專案共用模組。
function isEmpty(obj) {
return obj === undefined || obj === null || String(obj).trim() === '';
}
function isNotEmpty(obj) { return !isEmpty(obj); }
function getRealLength(str) {
return isEmpty(str) ? 0 : str.replace(/[^\x00-\xff]/g, "**").length;
}
// "abc中文" → 3 + 2*2 = 7
var class2type = {};
var toString = Object.prototype.toString;
"Boolean Number String Function Array Date RegExp Object".split(" ").forEach(function(name) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
function type(obj) {
return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
}
function isBoolean(obj) { return type(obj) === 'boolean'; }
function isNumeric(obj) { return type(obj) === 'number'; }
function isString(obj) { return type(obj) === 'string'; }
function isFunction(obj) { return type(obj) === 'function'; }
function isArray(obj) { return type(obj) === 'array'; }
function isDate(obj) { return type(obj) === 'date'; }
function isRegExp(obj) { return type(obj) === 'regexp'; }
function isObject(obj) { return type(obj) === 'object'; }
console.log(isEmpty("")); // true
console.log(isEmpty(" ")); // true
console.log(isNumeric(123)); // true
console.log(isNumeric("123")); // false
console.log(isArray([])); // true
console.log(isArray({})); // false
console.log(getRealLength("中文")); // 4
console.log(type(null)); // "null"
console.log(type(/regex/)); // "regexp"
isEmpty,避免 TypeErrorObject.prototype.toString 不可偽造,準確區分 Array/Date/RegExp 等內建型別toString.call 查表,無原型鏈查找開銷class2type 表建議封裝為 UMD/ESM 模組,配合 TypeScript 定義檔(.d.ts)提供型別提示。