UNPKG

@buession/prototype

Version:

A native object extension framework for Javascript.

1,482 lines (1,467 loc) 46.5 kB
/*! * Buession prototype v4.1.8 * * @link https://prototype.buession.com/ * @source https://github.com/buession/buession-prototype * @copyright @ 2020-2025 Buession.com Inc. * @license MIT * @Build Time Wed, 16 Apr 2025 15:22:35 GMT */ (function (factory) { typeof define === 'function' && define.amd ? define(factory) : factory(); })((function () { 'use strict'; /** * Prototype 对象 */ const Prototype = { /** * 版本 */ version: "v4.1.8", /** * 空方法 * * @return void */ emptyFunction: function () { }, /** * * @param x 任意参数 * @return 任意值 */ K: function (x) { return x; } }; window.Prototype = Prototype; /** * Try 对象 */ const Try = { /** * 接收任意数目的函数作为参数,返回第一个执行成功的函数(未抛出异常的函数)的结果 * * @return 任意函数参数执行结果 */ these: function () { let result; for (let i = 0; i < arguments.length; i++) { const lambda = arguments[i]; if (Object.isFunction(lambda)) { try { result = lambda(); break; } catch (e) { console.error(e); } } } return result; } }; window.Try = Try; /** * Optional 对象 */ class Optional { /** * 构造函数 * * @param value T 类型的值 */ constructor(value) { this.value = value; } /** * 返回一个指定 T 类型的值的 Optional 实例 * * @param value T 类型的值 * @return T 类型的值的 Optional 实例 */ static of(value) { return new Optional(value); } /** * 如果为非 null 或 undefined,返回 Optional 描述的指定值的实例,否则返回空的 Optional 实例 * * @param value T 类型的值 * @return T 类型的值的 Optional 实例,或空的 Optional 实例 */ static ofNullable(value) { return Object.isUndefinedOrNull(value) ? Optional.empty() : new Optional(value); } /** * 返回空的 Optional 实例 * * @return 空的 Optional 实例 */ static empty() { return new Optional(null); } /** * 如果 value 不为 null 或 undefined,则返回 value 的值;否则抛出异常 * * @return Optional 中包含这个值 */ get() { if (this.value === null || typeof this.value === "undefined") { throw "No value present"; } return this.value; } /** * 如果 value 不为 null 或 undefined,则返回 value 的值;否则返回 other * * @param other 其它值 * @return value 不为 null 或 undefined,则返回 value 的值;否则返回 other */ orElse(other) { return Object.isUndefinedOrNull(this.value) ? other : this.value; } /** * 如果 value 不为 null 或 undefined,则返回 true;否则返回 false * * @return value 不为 null 或 undefined,则返回 true;否则返回 false */ isPresent() { return Object.isUndefinedOrNull(this.value) === false; } } window.Optional = Optional; /** * Object 对象扩展 */ /** * 获取对象数据类型 * * @param obj 对象变量 * @return 对象数据类型 */ Object.type = function (obj) { return typeof obj; }; /** * 获取对象数据类型 * * @param obj 对象变量 * @return 对象数据类型 */ Object.rawType = function (obj) { return Object.prototype.toString.call(obj).slice(8, -1); }; /** * 判断对象是否为 object 类型 * * @param obj 任意对象 * @return boolean */ Object.isObject = function (obj) { return obj !== null && typeof obj === "object"; }; /** * 判断对象是否为 object 类型 * * @param obj 任意对象 * @return boolean */ Object.isPlainObject = function (obj) { return Object.prototype.toString.call(obj) === "[object Object]"; }; /** * 判断对象是否为 Map 类型 * * @param obj 任意对象 * @return boolean */ Object.isMap = function (obj) { return Object.prototype.toString.call(obj) === "[object Map]"; }; /** * 判断对象是否为 Set 类型 * * @param obj 任意对象 * @return boolean */ Object.isSet = function (obj) { return Object.prototype.toString.call(obj) === "[object Set]"; }; /** * 判断对象是否为函数 * * @param obj 任意对象 * @return boolean */ Object.isFunction = function (obj) { return Object.type(obj) === "function"; }; /** * 判断对象是否为 Symbol * * @param obj 任意对象 * @return boolean */ Object.isSymbol = function (obj) { if (typeof obj === "symbol") { return true; } try { const toString = Symbol.prototype.toString; if (typeof obj.valueOf() !== "symbol") { return false; } return /^Symbol\(.*\)$/.test(toString.call(obj)); } catch (e) { return false; } }; /** * 判断对象是否为 Promise * * @param obj 任意对象 * @return boolean */ Object.isPromise = function (obj) { return Object.isUndefinedOrNull(obj) === false && Object.isFunction(obj.then) === true && Object.isFunction(obj.catch) === true; }; /** * 判断对象是否为原始类型 * * @param obj 任意对象 * @return boolean */ Object.isPrimitive = function (obj) { return Object.isBoolean(obj) === true || Object.isString(obj) === true || Object.isNumber(obj) === true; }; /** * 判断对象是否为数组 * * @param obj 任意对象 * @return boolean */ Object.isArray = function (obj) { return Array.isArray(obj) === true; }; /** * 判断对象是否为字符串对象 * * @param obj 任意对象 * @return boolean */ Object.isString = function (obj) { return Object.type(obj) === "string"; }; /** * 判断对象是否为数字对象 * * @param obj 任意对象 * @return boolean */ Object.isNumber = function (obj) { return Object.type(obj) === "number"; }; /** * 判断对象是否为布尔对象 * * @param obj 任意对象 * @return boolean */ Object.isBoolean = function (obj) { return Object.type(obj) === "boolean"; }; /** * 判断对象是否为正则对象 * * @param obj 任意对象 * @return boolean */ Object.isRegExp = function (obj) { return Object.rawType(obj) === 'RegExp'; }; /** * 判断对象是否为文件对象 * * @param obj 任意对象 * @return boolean */ Object.isFile = function (obj) { return obj instanceof File; }; /** * 判断对象是否为 windows 对象 * * @param obj 任意对象 * @return boolean */ Object.isWindow = function (obj) { return Object.isUndefinedOrNull(obj) && obj == obj.window; }; /** * 判断对象是否为 Element * * @param obj 任意对象 * @return boolean */ Object.isElement = function (obj) { if (Object.isUndefinedOrNull(obj)) { return false; } return !!(obj.nodeType == 1); }; /** * 判断对象是否为事件对象 * * @param obj 任意对象 * @return boolean */ Object.isEvent = function (obj) { return obj instanceof Event; }; /** * 判断对象是否为 null 对象 * * @param obj 任意对象 * @return boolean */ Object.isNull = function (obj) { return obj === null; }; /** * 判断对象是否为未定义 * * @param obj 任意对象 * @return boolean */ Object.isUndefined = function (obj) { return obj === undefined; }; /** * 判断对象是否为未定义或 null * * @param obj 任意对象 * @return boolean */ Object.isUndefinedOrNull = function (obj) { return Object.isUndefined(obj) === true || Object.isNull(obj) === true; }; /** * 判断两个对象是否相等 * * @param obj1 一个对象 * @param obj2 用于和 obj1 比较的对象 * @return 当两个对象相等时,返回 true;否则,返回 false */ Object.equals = function (obj1, obj2) { if (obj1 === obj2) { return true; } else if (!(obj1 instanceof Object) || !(obj2 instanceof Object)) { return false; } else if (obj1.constructor !== obj2.constructor) { return false; } else if (Object.isArray(obj1) && Object.isArray(obj2) && obj1.length === obj2.length) { for (let i = 0; i < obj1.length; i++) { if (Object.equals(obj1[i], obj2[i]) === false) { return false; } } } else if (Object.isObject(obj1) && Object.isObject(obj2) && Object.keys(obj1).length === Object.keys(obj2).length) { for (const key in obj1) { if (obj1.hasOwnProperty.call(key)) { if (Object.equals(obj1[key], obj2[key]) === false) { return false; } } } } else { return false; } return true; }; /** * 克隆对象 * * @param obj 任意对象 * @return 新对象实例 */ Object.clone = function (obj) { if (Object.isString(obj)) { return String(obj); } else if (Object.isArray(obj)) { return Array.prototype.slice.apply(obj); } else if (Object.isPlainObject(obj)) { const result = Object.create(null); Object.keys(obj).forEach(key => { result[key] = Object.clone(obj[key]); }); return result; } return obj; }; /** * 克隆对象,但需要删除指定属性 * * @param obj 任意对象 * @param fields 需要删除的属性 * @return 新对象实例 */ Object.omit = function (obj, ...fields) { const result = Object.clone(obj); for (let i = 0; i < fields.length; i++) { const key = fields[i]; delete result[key]; } return result; }; /** * 返回对象指定属性,生成新对象 * * @param obj 任意对象 * @param fields 需要返回的属性 * @return 新对象实例 * @since 4.1.0 */ Object.pick = function (obj, ...fields) { const result = Object.create(null); fields.forEach((key) => { result[key] = Object.clone(obj[key]); }); return result; }; /** * Array 对象扩展 */ /** * 判断数组是否为空数组 * * @return boolean */ Array.prototype.isEmpty = function () { return this.length === 0; }; /** * 判断元素是否在数组中 * * @param item 查找对象 * @return boolean */ Array.prototype.exists = function (item) { return this.indexOf(item) !== -1; }; /** * 获取一个元素 * * @return 第一个元素 */ Array.prototype.first = function () { if (this.length === 0) { throw "Array index out of range: 0"; } return this[0]; }; /** * 获取一个元素 * * @return 第一个元素 */ Array.prototype.last = function () { if (this.length === 0) { throw "Array index out of range: 0"; } return this[this.length - 1]; }; /** * 数组迭代 * * @param callback 回调函数 * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ Array.prototype.each = Array.prototype.forEach; /** * 获取数组大小 * * @return 数组大小 */ Array.prototype.size = function () { return this.length; }; /** * 克隆数组 * * @return 克隆结果 */ Array.prototype.merge = Array.prototype.concat; /** * 返回一个不包含 null/undefined 值元素的数组的新版本 * * @return 不包含 null/undefined 值元素的数组的新版本 */ Array.prototype.compact = function () { return this.filter((value) => Object.isUndefinedOrNull(value) === false); }; /** * 对数组的元素进行去重 * * @return 数组元素进行去重后的新版本 */ Array.prototype.unique = function () { return Array.from(new Set(this)); }; /** * 返回不包括参数中任意一个指定值的数组 * * @param values 排除值数组 * @return 不包括参数中任意一个指定值的数组 */ Array.prototype.without = function (...values) { return this.filter((value) => values.includes(value) === false); }; /** * 克隆数组 * * @return 克隆结果 */ Array.prototype.clone = function () { return this.slice(0); }; /** * 清空数组 * * @return 空数组 */ Array.prototype.clear = function () { this.length = 0; return this; }; /** * Date 对象扩展 */ /** * 判断是否为闰年 * * @return boolean */ Date.prototype.isLeapYear = function () { const year = this.getFullYear(); return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; /** * 获取季节 * * @return 季节 */ Date.prototype.getSeason = function () { const month = this.getMonth(); if (month >= 3 && month <= 5) { return 0; } else if (month >= 6 && month <= 8) { return 1; } else if (month >= 9 && month <= 11) { return 2; } else if (month >= 12 || month <= 2) { return 3; } else { return 0; } }; /** * 获取年份中的第几天 * * @return 年份中的第几天 */ Date.prototype.getDayOfYear = function () { const daysInMonth = [31, this.isLeapYear() ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let days = 0; for (let m = 0, month = this.getMonth(); m < month; m++) { days += daysInMonth[m]; } return days; }; /** * 获取年份总天数 * * @return 年份总天数 */ Date.prototype.getDaysOfYear = function () { return this.isLeapYear() ? 366 : 365; }; /** * Format a date object into a string value. * @param format string - the desired format of the date * * The format can be combinations of the following: * * y - 年 * n - 季度(1 到 4) * N - 季度名称 * A - 季度中文名称 * M - 月 * f - 月(Jan 到 Dec) * F - 月(January 到 December) * C - 月,中文名称 * d - 日 * Y - 年份中的第几天(0 到 365) * T - 月份有几天(28 到 30) * j - 每月天数后面的英文后缀(st,nd,rd 或者 th) * e - 星期几,数字表示,0(表示星期天)到 6(表示星期六) * E - 星期几,数字表示,1(表示星期一)到 7(表示星期天) * l - 星期几,文本表示,3 个字母(Mon 到 Sun) * L - 星期几,完整的文本格式(Sunday 到 Saturday) * w - 星期几,中文名称 * W - 一月中第几个星期几 * i - 月份中的第几周 * o - 年份中的第几周 * h - 小时(1~12) * H - 小时(0~23) * m - 分 * s - 秒 * S - 毫秒 * a - 上午/下午标记 * O - 与格林威治时间相差的小时数 * P - 与格林威治时间相差的小时数,小时和分钟之间有冒号分隔 * Z - 时区 * * @return 格式化后的日期时间 */ Date.prototype.format = function (format) { if (Object.isString(format) === false) { throw "Invalid argument format"; } const _season_map = { "N": ["Spring", "Summer", "Autumn", "Winter"], "A": ["\u6625", "\u590f", "\u79cb", "\u51ac"] }; const _month_map = { "f": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "F": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], "C": ["\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D", "\u4E03", "\u516B", "\u4E5D", "\u5341", "\u5341\u4E00", "\u5341\u4E8C"] }; const _weekday_map = { "W": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], "WW": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], "WC": ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"] }; const seasonFn = () => { const month = this.getMonth(); if (month === 11 || month >= 0 && month <= 1) { return 1; } else if (month >= 2 && month <= 4) { return 2; } else if (month >= 5 && month <= 7) { return 3; } else if (month >= 8 && month <= 10) { return 4; } else { return 0; } }; const $funcs = { // 年 "y": (pattern) => { return (this.getFullYear() + "").substring(4 - pattern.length); }, // 季度(1 到 4) "n": () => { return seasonFn(); }, // 季度名称 "N": () => { return _season_map["N"][seasonFn() - 1]; }, // 季度中文名称 "A": () => { return _season_map["A"][seasonFn() - 1]; }, // 月 "M": (pattern) => { const $month = this.getMonth() + 1; const result = $month < 10 ? "0" + $month : "" + $month; return result.substring(2 - pattern.length); }, // 月(Jan 到 Dec) "f": () => { const $month = this.getMonth(); return _month_map["f"][$month]; }, // 月(January 到 December) "F": () => { const $month = this.getMonth(); return _month_map["F"][$month]; }, // 月,中文名称 "C": () => { const $month = this.getMonth(); return _month_map["C"][$month]; }, // 星期数字,0 到 6 表示 "e": () => { return this.getDay(); }, // 星期数字,1 到 7 表示 "E": () => { return this.getDay() + 1; }, // 星期英文缩写 "l": () => { const $weekday = this.getDay(); return _weekday_map["W"][$weekday]; }, // 星期英文全称 "L": () => { const $weekday = this.getDay(); return _weekday_map["WC"][$weekday]; }, // 星期中文名称 "w": () => { const $weekday = this.getDay(); return _weekday_map["WC"][$weekday]; }, // 日 "d": (pattern) => { const $date = this.getDate(); const result = $date < 10 ? "0" + $date : "" + $date; return result.substring(2 - pattern.length); }, // 小时 "h": (pattern) => { const $hour = this.getHours(); let result = $hour % 12 === 0 ? "12" : $hour % 12; result = $hour < 10 ? "0" + $hour : "" + $hour; return result.substring(2 - pattern.length); }, // 小时 "H": (pattern) => { const $hour = this.getHours(); const result = $hour < 10 ? "0" + $hour : "" + $hour; return result.substring(2 - pattern.length); }, // 分钟 "m": (pattern) => { const $minutes = this.getMinutes(); const result = $minutes < 10 ? "0" + $minutes : "" + $minutes; return result.substring(2 - pattern.length); }, // 秒钟 "s": (pattern) => { const $seconds = this.getSeconds(); const result = $seconds < 10 ? "0" + $seconds : "" + $seconds; return result.substring(2 - pattern.length); }, // 毫秒 "S": (pattern) => { const $mise = this.getMilliseconds(); const result = $mise < 10 ? "0" + $mise : "" + $mise; return result.substring(2 - pattern.length); } }; return format.replace(/([ynNAMfFCdYTjeElLwWiohHmsSaOPZ])+/g, (all, t) => { const fn = $funcs[t]; return Object.isFunction(fn) ? fn(all) : all; }); }; /** * Document 对象扩展 */ var SameSite; (function (SameSite) { SameSite["NONE"] = "None"; SameSite["LAX"] = "Lax"; SameSite["STRICT"] = "Strict"; })(SameSite || (SameSite = {})); class CookieInstance { constructor() { } set(name, value, options) { const $name = name = encodeURIComponent(name) .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent); const $value = value ? encodeURIComponent(value) .replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, decodeURIComponent) : ""; let stringifiedAttributes = ""; if (options) { stringifiedAttributes += options.domain ? "; domain=" + options.domain : ""; stringifiedAttributes += options.path ? "; path=" + options.path : ""; if (options.expires) { const $expiresDate = options.expires instanceof Date ? options.expires : new Date(Date.now() + options.expires * 864e5); stringifiedAttributes += "; expires=" + $expiresDate.toUTCString(); } if (Object.isUndefinedOrNull(options.sameSite) === false) { stringifiedAttributes += "; sameSite=" + options.sameSite; } if (Object.isBoolean(options.secure) && options.secure === true) { stringifiedAttributes += "; secure"; } if (Object.isBoolean(options.httpOnly) && options.httpOnly === true) { stringifiedAttributes += "; httpOnly"; } } return document.cookie = $name + "=" + $value + stringifiedAttributes; } get(name) { const cookies = document.cookie ? document.cookie.split("; ") : []; for (let i = 0; i < cookies.length; i++) { const parts = cookies[i].split("="); const $name = decodeURIComponent(parts[0]); let $value = parts.slice(1).join("="); if ($name === name) { if ($value[0] === '"') { $value = $value.slice(1, -1); } return $value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); } } return null; } delete(name, options) { const $options = options ? options : {}; $options.expires = -1; this.set(name, "", $options); } } /** * 检测当前浏览器是否为全屏 * * @return 当前浏览器是否为全屏 */ Object.defineProperty(document, "fullScreen", { value: Object.isUndefined(document.fullscreen) === false ? document.fullscreen : (Object.isUndefined(document.mozFullScreen) === false ? document.mozFullScreen : (Object.isUndefined(document.webkitIsFullScreen) === false ? document.webkitIsFullScreen : (Object.isUndefined(document.msFullScreen) === false ? document.msFullScreen : (Object.isUndefined(document.fullscreenElement) === false ? document.fullscreenElement !== null : (Object.isUndefined(document.mozFullScreenElement) === false ? document.mozFullScreenElement !== null : (Object.isUndefined(document.webkitFullscreenElement) === false ? document.webkitFullscreenElement !== null : (Object.isUndefined(document.msFullscreenElement) === false ? document.msFullscreenElement !== null : false))))))), configurable: true, writable: false }); /** * 检测当前浏览器是否支持全屏模式 * * @return 当前浏览器是否支持全屏模式 */ Object.defineProperty(document, "fullScreenEnabled", { value: Object.isUndefined(document.mozFullScreenEnabled) === false ? document.mozFullScreenEnabled : (Object.isUndefined(document.webkitFullscreenEnabled) === false ? document.webkitFullscreenEnabled : (Object.isUndefined(document.msFullscreenEnabled) === false ? document.msFullscreenEnabled : (Object.isUndefined(document.fullscreenEnabled) === false ? document.fullscreenEnabled : false))), configurable: true, writable: false }); /** * 返回当前文档中正在以全屏模式显示的 Element 节点 * * @return 当前文档中正在以全屏模式显示的 Element 节点 */ Object.defineProperty(document, "fullScreenElement", { value: Object.isUndefined(document.mozFullScreenElement) === false ? document.mozFullScreenElement : (Object.isUndefined(document.webkitFullscreenElement) === false ? document.webkitFullscreenElement : (Object.isUndefined(document.msFullscreenElement) === false ? document.msFullscreenElement : (Object.isUndefined(document.fullscreenElement) === false ? document.fullscreenElement : null))), configurable: true, writable: false }); /** * 返回 Cookie 对象 * * @return Cookie 对象 */ Object.defineProperty(document, "httpCookie", { value: new CookieInstance(), configurable: true, writable: false }); /** * 请求进入全屏模式 * * @return Promise */ Document.prototype.requestFullscreen = function () { const doc = document.documentElement; if (Object.isFunction(doc.mozRequestFullScreen)) { return doc.mozRequestFullScreen(); } else if (Object.isFunction(doc.webkitRequestFullscreen)) { return doc.webkitRequestFullscreen(); } else if (Object.isFunction(doc.msRequestFullscreen)) { return doc.msRequestFullscreen(); } else { return doc.requestFullscreen(); } }; /** * 退出全屏模式 * * @return Promise */ Document.prototype.exitFullscreen = function () { if (Object.isFunction(document.mozCancelFullScreen)) { return document.mozCancelFullScreen(); } else if (Object.isFunction(document.mozExitFullScreen)) { return document.mozExitFullScreen(); } else if (Object.isFunction(document.webkitCancelFullScreen)) { return document.webkitCancelFullScreen(); } else if (Object.isFunction(document.webkitExitFullscreen)) { return document.webkitExitFullscreen(); } else if (Object.isFunction(document.msExitFullscreen)) { return document.msExitFullscreen(); } else { return document.exitFullscreen(); } }; /** * Function 对象扩展 */ /** * 获取函数参数名称 * * @return 函数参数名称列表 */ Function.prototype.argumentNames = function () { const method = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/); if (method === null) { return null; } const names = method[1].replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, "").replace(/\s+/g, "").split(", "); return names.length === 1 && !names[0] ? [] : names; }; /** * 延时执行函数 * * @param timeout 延时时间(单位:秒) * @return mixed */ Function.prototype.delay = function (timeout) { const __method = this; const args = Array.prototype.slice.call(arguments, 1); return setTimeout(__method.apply(__method, args), timeout * 1000); }; /** * Math 对象扩展 */ /** * 产生一个指定范围内的随机数 * * @param min 返回的最低值(默认 0) * @param max 返回的最高值 * @return 随机数 */ Math.rand = function (min, max) { min = min || 0; max = max || Number.MAX_SAFE_INTEGER; const rand = Math.random() * (max - min + 1) + min; const result = Math.round(rand); if (result < min) { return min; } else if (result > max) { return max; } else { return result; } }; /** * Number 对象扩展 */ /** * 数字填充 * * @param length 长度 * @param radix 进制 * @return 填充后的字符串数字 */ Number.prototype.toPaddedString = function (length, radix) { const str = this.toString(radix || 10); return "0".repeat(length - str.length) + str; }; /** * 判断数字是否为奇数 * * @param num 需要判断的数字 * @return boolean 数字是为奇数返回 true;否则返回 false */ Number.isOdd = function (num) { return num % 2 === 1; }; /** * 判断数字是否为偶数 * * @param num 需要判断的数字 * @return boolean 数字是为偶数返回 true;否则返回 false */ Number.isEven = function (num) { return num % 2 === 0; }; /** * 判断一个数字是否在另两个数字之间 * * @param num 需要判断的数 * @param min 最小值 * @param max 最大值 * @param match 是否包含最小值或最大值 * @return boolean 数字是否在另两个数字之间,返回 true;否则返回 false */ Number.isBetween = function (num, min, max, match = false) { min = min || 0; max = max || 0; if (min > max) { min ^= max; max ^= min; min ^= max; } return match == true ? num >= min && num <= max : num > min && num < max; }; /** * String 对象扩展 */ /** * 判断字符串是否存在 * * @param str 子字符串 * @return boolean */ String.prototype.exists = function (str) { return this.indexOf(str) >= 0; }; /** * 判断字符串是否相等 * * @param str 与此 String 进行比较的对象 * @return boolean */ String.prototype.equals = function (str) { return Object.isUndefinedOrNull(str) === false && this === str; }; /** * 判断字符串是否相等,不考虑大小写 * * @param str 与此 String 进行比较的对象 * @return boolean */ String.prototype.equalsIgnoreCase = function (str) { return str !== undefined && str !== null && this.toLowerCase() === str.toLowerCase(); }; /** * 判断是否为空字符串 * * @return boolean */ String.prototype.isEmpty = function () { return this.length === 0; }; /** * 判断是否不为空字符串 * * @return boolean */ String.prototype.isNotEmpty = function () { return this.length > 0; }; /** * 判断是否为空白字符串 * * @return boolean */ String.prototype.isBlank = function () { return this.length === 0 || this.trim().length === 0; }; /** * 判断是否不为空白字符串 * * @return boolean * @since4.0.2 */ String.prototype.isNotBlank = function () { return this.isBlank() === false; }; /** * 重复一个字符串 * * @papram count 重复次数 * @return 重复后的字符串 */ String.prototype.repeat = function (count) { if (count < 1) { return ""; } else { const s = this.toString(); let result = s; for (let i = 0; i < count; i++) { result += s; } return result; } }; /** * 截取字符串左边边指定数目的字符串 * * @param length 截取长度 * @return 子字符串 */ String.prototype.left = function (length) { return this.substring(0, length); }; /** * 截取字符串右边指定数目的字符串 * * @param length 截取长度 * @return 子字符串 */ String.prototype.right = function (length) { return this.substring(this.length - length, this.length); }; /** * 截取字符串,超出部分用 truncation 替代 * * @param length 截取长度 * @param truncation 替换字符串 * @return 截取后的字符串 * 实际截取长度:当 length 小于等于 truncation 的长度时为,length;当 length 大于 truncation 的长度时为,length - truncation.length */ String.prototype.truncation = function (length, truncation) { truncation = truncation || "..."; return this.length > length ? this.slice(0, length <= truncation.length ? length : length - truncation.length) + truncation : String(this); }; /** * 删除字符串开头的空白字符 * * @return 删除了字符串最左边的空白字符的字符串 */ String.prototype.ltrim = function () { return Object.isFunction(this.trimStart) ? this.trimStart() : this.replace(/^\s*/g, ""); }; /** * 删除字符串结尾的空白字符 * * @return 删除了字符串最右边的空白字符的字符串 */ String.prototype.rtrim = function () { return Object.isFunction(this.trimEnd) ? this.trimEnd() : this.replace(/\s*$/g, ""); }; /** * 判断字符串是否以给定的字符串开头 * * @param str 搜索的字符串 * @return boolean */ String.prototype.startsWith = function (str) { return this.indexOf(str) === 0; }; /** * 判断字符串是否以给定的字符串结尾 * * @param str 搜索的字符串 * @return boolean */ String.prototype.endsWith = function (str) { const d = this.length - str.length; return d >= 0 && this.lastIndexOf(str) === d; }; /** * 首字母小写 * * @return 结果字符串 */ String.prototype.lcfirst = function () { return this.charAt(0).toLowerCase() + this.substring(1); }; /** * 首字母大写 * * @return 结果字符串 */ String.prototype.ucfirst = function () { return this.charAt(0).toUpperCase() + this.substring(1); }; /** * 将 HTML 编码 * * @return 编码后的字符串 */ String.prototype.escapeHTML = function () { return this.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); }; /** * 将 HTML 实体字符解码 * * @return 解码后的字符串 */ String.prototype.unescapeHTML = function () { return this.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&"); }; /** * 删除 HTML 标签 * * @param tag HTML 标签 * @returns 删除标签后的字符串 */ String.prototype.stripTag = function (tag) { return this.replace(new RegExp("<" + tag + "(\\s+(\"[^\"]*\"|'[^']*'|[^>])+)?(\/)?>|<\/" + tag + ">", "gi"), ""); }; /** * 批量删除 HTML 标签 * * @param tags 删除指定的标签 * @return 删除标签后的字符串 */ String.prototype.stripTags = function (tags) { if (typeof tags === "string") { return this.stripTag(tags); } else if (Array.isArray(tags)) { let result = this.toString(); for (let i = 0; i < tags.length; i++) { result = result.stripTag(tags[i]); } return result; } else { return this.toString(); } }; /** * 删除 script 标签 * * @return 删除 script 标签后的字符串 */ String.prototype.stripScripts = function () { return this.replace(/<script[^>]*>([\S\s]*?)<\/script>/img, ""); }; /** * 将字符串转换为数组 * * @param delimiter 分隔字符 * @return 数组 */ String.prototype.toArray = function (delimiter) { return this.split(delimiter || ""); }; /** * 返回一个数组的字符串表示形式 * * @param useDoubleQuotes 是否使用双引号引住 * @return 后的字符串 */ String.prototype.inspect = function (useDoubleQuotes) { const specialChar = { '\b': '\\b', '\t': '\\t', '\r': '\\r', '\n': '\\n', '\f': '\\f', '\\': '\\\\' }; const escapedString = this.replace(/[\x00-\x1f\\]/g, (character) => { if (character in specialChar) { return specialChar[character]; } return '\\u00' + character.charCodeAt(0).toPaddedString(2, 16); }); if (useDoubleQuotes) { return '"' + escapedString.replace(/"/g, '\\"') + '"'; } else { return "'" + escapedString.replace(/'/g, '\\\'') + "'"; } }; /** * 获取字符串 hash code * * @return 字符串 hash code */ String.prototype.hashCode = function () { let result = 0; if (result === 0 && this.length > 0) { for (let i = 0; i < this.length; i++) { result = 31 * result + this.charCodeAt(i); } } return result; }; /** * 生成随机字符串 * * @param length 生成字符串的长度 * @param type 生成类型 / 随机字符串范围 * NUMERIC - 数字随机字符串 * LETTER - 英文随机字符串 * LETTER_NUMERIC - 英文数字混合随机字符串 * CHINESE - 中文随机字符串 * * @return 生成结果 */ String.random = function (length, type = "LETTER_NUMERIC") { let result = ""; if (type === "CHINESE") { for (let i = 0; i < length; i++) { result += String.fromCharCode(Math.rand(19968, 40891)); } return result; } const numeric = "0123456789"; const letter = "abcdefghijklmnopqrstuvwxyz"; let characters; if (type === "NUMERIC") { characters = numeric; } else if (type === "LETTER") { characters = letter + letter.toUpperCase(); } else if (type === "LETTER_NUMERIC" || Object.isUndefinedOrNull(type)) { characters = numeric + letter + letter.toUpperCase(); } else if (Object.isString(type)) { characters = type; } else { throw "Invalid argument type value, must be: NUMERIC, LETTER, LETTER_NUMERIC, CHINESE or String Characters"; } let l; for (let j = 0; j < length; j++) { l = Math.rand(0, characters.length - 1); result += characters[l]; } return result; }; /** * 生成 UUID * * @return UUID * @since 4.0.0 */ String.guid = function () { function s() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); } return s() + s() + "-" + s() + "-" + s() + "-" + s() + "-" + s() + s() + s(); }; /** * Window 对象扩展 */ const isMobile = ["Android", "iPhone", "iPod", "Windows Phone", "Mobile", "Coolpad", "mmp", "SmartPhone", "midp", "wap", "xoom", "Symbian", "J2ME", "Blackberry", "Wince"].some((value) => navigator.userAgent.exists(value)); const isChrome = /\(KHTML, like Gecko\) Chrome\//.test(navigator.userAgent); const isFirefox = navigator.userAgent.exists("Firefox"); const isMozilla = navigator.userAgent.exists("Mozilla"); const isEdge = navigator.userAgent.exists("Edge"); const isMSIE = navigator.userAgent.exists("MSIE") && navigator.userAgent.exists("compatible"); const isOpera = navigator.userAgent.exists("Opera"); const isSafari = navigator.userAgent.exists("Safari"); const isNetscape = /Netscape([\d]*)\/([^\s]+)/i.test(navigator.userAgent); Object.defineProperty(window, "browser", { value: { userAgent: navigator.userAgent, name: navigator.appName, version: navigator.appVersion, cookieEnabled: navigator.cookieEnabled, language: navigator.language, languages: navigator.languages, isMobile: isMobile, isChrome: isChrome, isFirefox: isFirefox, isMozilla: isMozilla, isEdge: isEdge, isMSIE: isMSIE, isOpera: isOpera, isSafari: isSafari, isNetscape: isNetscape }, configurable: true, writable: false }); /** * 将字符串复制到剪贴板 * * @param str 字符串 */ Window.prototype.copy = function (str) { try { if (Object.isObject(this.clipboardData) === true) { this.clipboardData.setData("text", str); } else { const fakeElement = document.createElement("textarea"); fakeElement.style.border = "none"; fakeElement.style.margin = "0"; fakeElement.style.padding = "0"; fakeElement.style.position = "absolute"; fakeElement.style.top = "-9999px"; fakeElement.style.left = "-9999px"; fakeElement.value = str; fakeElement.setAttribute("readonly", ""); document.body.appendChild(fakeElement); fakeElement.setSelectionRange(0, str.length); fakeElement.select(); document.execCommand("copy"); fakeElement.remove(); } } catch (e) { console.error(e); } }; /** * 延时执行 * * @param func 延时执行方法 * @param wait 延时时长(单位:毫秒) * @param args 方法参数 * * @return 方法执行结果 */ Window.prototype.delay = function (func, wait, ...args) { const delayFunc = (func, wait, ...args) => { if (typeof func !== "function") { throw new TypeError("Expected a function"); } return setTimeout(function () { func.apply(undefined, args); }, wait); }; return delayFunc(func, wait || 0, args); }; /** * 获取所有的请求参数及值 * * @return 所有的请求参数及值 */ Location.prototype.getParameters = function () { let queryString = this.search; const parameters = {}; if (queryString.indexOf("?") !== -1) { queryString = queryString.substring(1); const parts = queryString.split("&"); for (let i = 0; i < parts.length; i++) { const temp = parts[i].split("="); const val = temp.length == 2 ? encodeURIComponent(temp[1]) : ""; if (Object.isUndefined(parameters[temp[0]])) { parameters[temp[0]] = val; } else { if (Object.isArray(parameters[temp[0]]) === false) { const oldVal = parameters[temp[0]]; delete parameters[temp[0]]; parameters[temp[0]] = [oldVal]; } parameters[temp[0]].push(val); } } } return parameters; }; /** * 获取指定请求参数的值 * * @param name 参数名 * @return 指定请求参数的值 */ Location.prototype.getParameter = function (name) { const parameters = this.getParameters(); return parameters[name]; }; })); //# sourceMappingURL=prototype.umd.js.map