UNPKG

fenzhi-utils

Version:

分值前端项目的js函数库

1,521 lines (1,424 loc) 56.4 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Fenzhi = {})); })(this, (function (exports) { 'use strict'; /** * 平铺数组 * @param {array} arr 要平铺的数组 * @param {string} childProp 平铺的子集字段 * @param {boolean} keepChildren 是否删除子集(默认删除) * @returns {array} 返回平铺后的数组 */ /* let arr = [ { id: 1, children: [ { id: 2, children: [ { id: 4, children: [{ id: 8 }, { id: 9 }], }, { id: 5, children: [{ id: 10 }, { id: 11 }], }, ], }, { id: 3, children: [ { id: 6, children: [{ id: 12 }, { id: 13 }], }, { id: 7, children: [{ id: 14 }, { id: 15 }], }, ], }, ], }, { id: 101, }, ]; CustomArrayFlatter(arr) CustomArrayFlatter(arr, 'children') CustomArrayFlatter(arr, 'children', true) */ function CustomArrayFlatter() { var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var childrenKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'children'; var keepChildren = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var result = []; var newArr = JSON.parse(JSON.stringify(arr)); newArr.forEach(function (item) { var children = item[childrenKey]; if (!keepChildren) { delete item[childrenKey]; } result.push(item); if (Array.isArray(children)) { result = result.concat(CustomArrayFlatter(children, childrenKey, keepChildren)); } }); return result; } // 下面的方法可替换JSON.parse(JSON.stringify(arr)) // function deepCopy(source) { // if (typeof source != 'object') { // return source; // } // if (source == null) { // return source; // } // var newObj = source.constructor === Array ? [] : {}; //开辟一块新的内存空间 // for (var i in source) { // newObj[i] = deepCopy(source[i]); // } // return newObj; // } /** * 对一个由对象组成的数组进行排序 * @param {Array} arr arr 要排序的数组 * @param {String} prop 要排序的属性名 * @param {String} order 排序方式,默认为降序排序 * @returns {Array<Object>} 排序后的数组 */ /* // 测试数组 const list = [ { id: 6, name: 'John', age: true, score: 70.5, active: true }, { id: 5, name: '', age: '20', score: 80.5, active: false }, { id: 9, name: 'Amy', age: '20', score: 80.5, active: true }, { id: 15, name: 'Ian', age: '20', score: 80.5, active: false }, { id: 8, name: 'Lucy', age: '25', score: 75.5, active: false }, { id: 13, name: 'Grace', age: '30', score: 75.5, active: true }, { id: 2, name: 'Jerry', age: '20', score: 85.5, active: false }, { id: 3, name: 'Bob', age: '30', score: 85.5, active: true }, { id: 10, name: 'Frank', age: '30', score: 85.5, active: true }, { id: 11, name: 'David', age: '', score: 85.5, active: false }, { id: 4, name: 'Alice', age: '25', score: '', active: true }, { id: 14, name: 'Henry', age: '25', score: 85.5, active: true }, { id: 1, name: 'Tom', age: '25', score: 90.5, active: true }, { id: 12, name: 'Eva', age: '20', score: 90.5, active: true }, { id: 7, name: 'Mike', age: '30', score: 85.5, active: true }, ]; console.log(CustomArraySort(list, 'age', 'desc')); */ function CustomArraySort(arr, prop) { var order = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'desc'; if (!Array.isArray(arr)) return arr; if (typeof prop !== 'string' || !prop.trim()) return arr; if (!['asc', 'desc'].includes(order)) return arr; var compare = function compare(a, b) { return order === 'asc' ? a - b : b - a; }; return arr.sort(function (a, b) { if (isNaN(parseFloat(a[prop]))) return 1; if (isNaN(parseFloat(b[prop]))) return -1; var aValue = parseFloat(a[prop]); var bValue = parseFloat(b[prop]); if (aValue === bValue) return arr.indexOf(a) - arr.indexOf(b); return compare(aValue, bValue); }); } /** * 数组求和(根据某个字段求和) * @param {array} arr 求和的数组 * @returns {number} */ /** let arr_1 = [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }, { a: 5 }]; CustomArraySumField(arr_1, 'a'); // 15 let arr_2 = [ { a: 1 }, { a: null }, { a: '' }, { a: '1' }, { a: undefined }, { a: Infinity }, ]; CustomArraySumField(arr_2,'a');// 2 */ function CustomArraySumField() { var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var field = arguments.length > 1 ? arguments[1] : undefined; if (!arr.length) return 0; if ([0, 1].includes(arguments.length)) return 0; return arr.reduce(function (pre, item) { var curNum = 0; if ([null, 'null', '', 'undefined', undefined, Infinity].includes(item[field])) curNum = 0;else if (typeof item[field] === 'number') curNum = item[field];else if (typeof item[field] === 'string') curNum = parseInt(item[field], 10);else if (typeof item[field] === 'boolean') curNum = item[field] ? 1 : 0; return pre + curNum; }, 0); } /** * 数组求和 * @param {array} arr 求和的数组 * @returns {number} */ /** let arr_1 = [1,2,3,4,5,null,'',undefined,Infinity] CustomArraySumSignle(arr_1);// 15 let arr_2 = [1, 2, 3, 4, 5, 6]; CustomArraySumSignle(arr_2);// 21 */ function CustomArraySumSignle() { var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; if (!arr.length) return 0; return arr.reduce(function (pre, item) { var curNum = 0; if ([null, 'null', '', 'undefined', undefined, Infinity].includes(item)) curNum = 0;else if (typeof item === 'number') curNum = item;else if (typeof item === 'string') curNum = parseInt(item, 10);else if (typeof item === 'boolean') curNum = item ? 1 : 0; return pre + curNum; }, 0); } /** * 将数组组装成树形结构 * @param {array} arr 进行组装的数组 * @param {string} id 子级的字段 * @param {string} pid 父级的字段 * @param {string} childrenKey 子级集合的字段 * @returns {array} 返回组装后的数组 */ /* var arr = [ { id: 1, parent: null }, { id: 101, parent: null }, { id: 2, parent: 1 }, { id: 3, parent: 1 }, { id: 4, parent: 2 }, { id: 5, parent: 2 }, { id: 6, parent: 3 }, { id: 7, parent: 3 }, { id: 8, parent: 4 }, { id: 9, parent: 4 }, { id: 10, parent: 5 }, { id: 11, parent: 5 }, { id: 12, parent: 6 }, { id: 13, parent: 6 }, { id: 14, parent: 7 }, { id: 15, parent: 7 }, ]; var tree = CustomArrayToTree(arr, 'id', 'parent', 'childred') */ function CustomArrayToTree(arr) { var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'id'; var pid = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'pid'; var childrenKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'children'; var map = new Map(); var roots = []; arr.forEach(function (item) { map.set(item[id], item); }); arr.forEach(function (item) { var parent = map.get(item[pid]); if (parent) { if (!parent[childrenKey]) { parent[childrenKey] = []; } parent[childrenKey].push(item); } else { roots.push(item); } }); return roots; } /** * 格式化时间 * @param {string,date} date 时间 * @param {string} fmt 指定的格式化格式 * @returns {string} '' */ /* 下面是测试用例 CustomDateFtt(1565059668200,"yyyy-MM-dd hh:mm:ss");// '2019-08-06 10:47:48' CustomDateFtt(1565059668200,"yyyy-MM-dd");// '2019-08-06' CustomDateFtt('2022-02-14T13:30:00.000Z',"yyyy-MM-dd");// '2019-08-06' CustomDateFtt(new Date(),"yyyy-MM-dd");// '2019-08-06' CustomDateFtt(new Date('2022-01-01'),"yyyy-MM-dd");// '2022-01-01' CustomDateFtt(null, 'yyyy-MM-dd hh:mm:ss');// '' CustomDateFtt(undefined, 'yyyy-MM-dd hh:mm:ss');// '' CustomDateFtt('', 'yyyy-MM-dd hh:mm:ss');// '' CustomDateFtt('2022-01-01', 'yyyy-MM-dd');// '2022-01-01' CustomDateFtt('2022-01-01 12:34:56', 'yyyy-MM-dd hh:mm:ss');// '2022-01-01 12:34:56' CustomDateFtt('2022/01/01 12:34:56', 'yyyy-MM-dd hh:mm:ss');// '2022-01-01 12:34:56' CustomDateFtt('2022-01-01 12:34:56', 'yyyy/MM/dd hh:mm:ss');// '2022/01/01 12:34:56' CustomDateFtt('2022-01-01 12:34:56.123', 'yyyy-MM-dd hh:mm:ss.SSS');// '2022-01-01 12:34:56.123SS' CustomDateFtt('2022-01-01 12:34:56.123', 'yyyy-MM-dd hh:mm:ss.S');// '2022-01-01 12:34:56.123' CustomDateFtt('2022-01-01 12:34:56.123', 'yyyy-MM-dd hh:mm:ss.SS');// '2022-01-01 12:34:56.123S' CustomDateFtt('2022-01-01 12:34:56.123', 'yyyy-MM-dd hh:mm:ss.SSSS');// '2022-01-01 12:34:56.123SSS' CustomDateFtt('2022-01-01 12:34:56.123', 'yyyy-MM-dd hh:mm:ss.SSSSS'); // '2022-01-01 12:34:56.123SSSS' */ function CustomDateFtt(date, fmt) { if (date != null && date != '' && date != undefined) { if (typeof date == 'string') { if (date.includes('T')) { date = new Date(date); } else { date = date.replace(/-/g, '/'); } } var date = new Date(date); var o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds(), 'q+': Math.floor((date.getMonth() + 3) / 3), //季度 S: date.getMilliseconds() //毫秒 }; o.S < 100 && (o.S = o.S < 10 ? '00' + o.S : '0' + o.S); if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)); } else { fmt = ''; } return fmt; } /** * 获取时间所在月份起止日期 * @param {date} params 时间,不传默认当前 * @returns {array} */ /** CustomMonthRate(); // ['2023-3-01', '2023-3-31'] CustomMonthRate('2023-05-01'); // ['2023-5-01', '2023-5-31'] CustomMonthRate('2023-05-31'); // ['2023-5-01', '2023-5-31'] CustomMonthRate(new Date()); // ['2023-3-01', '2023-3-31'] CustomMonthRate('2023-02-21'); //  ['2023-2-01', '2023-2-28'] */ function CustomMonthRate(params) { var date; if (!arguments.length) { date = new Date(); } else { if ([null, '', undefined].includes(params)) { return ['', '']; } else { date = new Date(params); } } var year = date.getFullYear(); var month = date.getMonth() + 1; var lastDate = new Date(year, month, 0).getDate(); return ["".concat(year, "-").concat(month, "-01"), "".concat(year, "-").concat(month, "-").concat(lastDate)]; } /** * 获取本周时间 * @param {number} n 代表要获取周几的数字 * @param {date} time 代表要获取的时间 * @returns {string} 返回获取到的周几的时间 */ /** CustomWeekTime(0,'2023-04-03');// 【周一 ~ 周日】 获取周一 '2023-04-03' CustomWeekTime(-6,'2023-04-03');// 【周一 ~ 周日】 获取周日 '2023-04-09' CustomWeekTime(1,'2023-04-03');// 【周日 ~ 周六】 获取周日 '2023-04-02' CustomWeekTime(-5,'2023-04-03');// 【周日 ~ 周六】 获取周六 '2023-04-08' */ function CustomWeekTime(n, time) { var now = new Date(time); var year = now.getFullYear(); var month = now.getMonth() + 1; var date = now.getDate(); var day = now.getDay(); if (day !== 0) { n = n + (day - 1); } else { n = n + day; } if (day) { if (month > 1) { month = month; } else { year = year - 1; month = 12; } } now.setDate(now.getDate() - n); year = now.getFullYear(); month = now.getMonth() + 1; date = now.getDate(); s = year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date); return s; } /** * 将传入的数字乘以100并保留指定位数的小数,如果无法转换为数字则返回空字符串。 * @param {number} data 要转换的百分数 * @param {number} num 保留几位小数 * @returns {string} 返回转换后的百分数 */ /** test('CustomConverPercent', () => { expect(CustomConverPercent(0.123456)).toBe('12.35') expect(CustomConverPercent(0.123456, 3)).toBe('12.346') expect(CustomConverPercent('0.123456')).toBe('12.35') expect(CustomConverPercent('0.123456', 3)).toBe('12.346') expect(CustomConverPercent('')).toBe('') expect(CustomConverPercent(null)).toBe('') expect(CustomConverPercent(undefined)).toBe('') expect(CustomConverPercent(Infinity)).toBe('') }) */ function CustomConverPercent(data) { var num = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; data = parseFloat(data); // 如果不能强制转换为数字 比如:null undefined ''等 则返回 '' if (isNaN(data) || data === Infinity) return ''; data *= 100; return data.toFixed(num); } /** * 是否可以转换成数字 * @param {*} n 检测类型 * @returns {boolean} */ /** CustomIsNumeric(42); // true CustomIsNumeric('42'); // true CustomIsNumeric(' 42 '); // true CustomIsNumeric('4.2'); // true CustomIsNumeric('4,2'); // false CustomIsNumeric(''); // false CustomIsNumeric(' '); // false CustomIsNumeric(null); // false CustomIsNumeric(undefined); // false CustomIsNumeric(NaN); // false CustomIsNumeric(Infinity); // false CustomIsNumeric(-Infinity); // false */ function CustomIsNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } /** * 保留小数(非四舍五入) * @param {*} n * @param {*} fixed * @returns */ /** console.log(CustomNumberNoFixed(10.123456, 2)); // 10.12 console.log(CustomNumberNoFixed(-10.123456, 2)); // -10.12 console.log(CustomNumberNoFixed(NaN, 2)); // - console.log(CustomNumberNoFixed(null, 2)); // - console.log(CustomNumberNoFixed('', 2)); // - console.log(CustomNumberNoFixed(undefined, 2)); // - console.log(CustomNumberNoFixed(Number.MAX_SAFE_INTEGER, 2)); // 9007199254740991 console.log(CustomNumberNoFixed(Number.MIN_SAFE_INTEGER, 2)); // -9007199254740991 */ function CustomNumberNoFixed(n, fixed) { var num = parseFloat(n); if (isNaN(num)) { return '-'; } return ~~(Math.pow(10, fixed) * num) / Math.pow(10, fixed); } /** * 保留小数(四舍五入) * @param {number} num * @param {number} digits * @returns {string} * 注:js自带的toFixed有银行家算法缺陷,故重写 例:toFixed(1.255, 2) */ /* CustomNumberToFixed(1.2555, 2); // '1.26' CustomNumberToFixed(-1.2555, 2); // '-1.26' CustomNumberToFixed('1.2555', 2); // '1.26' CustomNumberToFixed('-1.2555', 2); // '-1.26' CustomNumberToFixed(1.2333, 2); // '1.23' CustomNumberToFixed(-1.2333, 2); // '-1.23' CustomNumberToFixed(1.2366, 2); // '1.24' CustomNumberToFixed(-1.2366, 2); // '-1.24' */ function CustomNumberToFixed(num) { var digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; if (isNaN(parseFloat(num)) || parseFloat(num) === Infinity) return ''; var zeroStrNum = num.toString(); // 处理科学计算情况 if (zeroStrNum.includes('e')) { var m = zeroStrNum.match(/\d(?:\.(\d*))?e([+-]\d+)/); zeroStrNum = num.toFixed(Math.max(0, (m[1] || '').length - m[2])); } var isNegativeNum = false; // 判断是否为负数 if (zeroStrNum.startsWith('-')) { isNegativeNum = true; zeroStrNum = zeroStrNum.slice(1); } // 获取小数点位置 var dotIndex = zeroStrNum.indexOf('.'); // 如果是整数/保留小数位数等于超过当前小数长度,则直接用toFixed返回 if (dotIndex === -1 || zeroStrNum.length - (dotIndex + 1) <= digits) { return num.toFixed(digits); } // 找到需要进行四舍五入的部分 var numArr = zeroStrNum.match(/\d/g) || []; numArr = numArr.slice(0, dotIndex + digits + 1); // 核心处理逻辑 if (parseInt(numArr[numArr.length - 1], 10) > 4) { // 如果最后一位大于4,则往前遍历+1 for (var i = numArr.length - 2; i >= 0; i--) { numArr[i] = String(parseInt(numArr[i], 10) + 1); // 判断这位数字 +1 后会不会是 10 if (numArr[i] === '10') { // 10的话处理一下变成 0,再次for循环,相当于给前面一个 +1 numArr[i] = '0'; } else { // 小于10的话,就打断循环,进位成功 break; } } } // 将小数点加入数据 numArr.splice(dotIndex, 0, '.'); // 处理多余位数 numArr.pop(); // 如果事负数,添加负号 if (isNegativeNum) { numArr.unshift('-'); } return Number(numArr.join('')).toFixed(digits); } /** * 转换单位后的数字 * @param {number} num 格式化的谁 * @param {number} digits 保留小数位 * @returns {string} 转换单位后的数字 */ /** CustomTendToNumber(); // '' CustomTendToNumber(113456789); // '1.13' CustomTendToNumber(-110000000); // '-1.10' CustomTendToNumber(11000); // '1.10' CustomTendToNumber(-11000); // '-1.10' CustomTendToNumber(11); // '11' */ function CustomTendToNumber(num) { var digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; if (!CustomIsNumeric(num)) return ''; num = parseFloat(num); var character = num >= 0 ? '' : '-'; // 符号 var shortNum = Math.abs(num); if (shortNum >= 100000000) { shortNum = CustomNumberToFixed(shortNum / 100000000, digits); } else if (shortNum >= 10000) { shortNum = CustomNumberToFixed(shortNum / 10000, digits); } return character + shortNum; } /** * 获取数字的单位 * @param {number} num 转换的数组 * @returns {string} 返回的单位 */ /** CustomTendToUnit(100000000); // 亿 CustomTendToUnit(10000); // 万 CustomTendToUnit(9999); // '' CustomTendToUnit(null); // '' CustomTendToUnit(undefined); // '' CustomTendToUnit(NaN); // '' CustomTendToUnit(Infinity); // '' */ function CustomTendToUnit(num) { if (!CustomIsNumeric(num)) return ''; num = Math.abs(num); var nuit = ''; if (num >= 100000000) { nuit = '亿'; } else if (num >= 10000) { nuit = '万'; } return nuit; } /** * 数字转换单位 * @param {number} num 转换的数字 * @param {number} digits 保留的小数位数 * @returns {string} 返回转换的数字 */ /** CustomTendToTurn(); // '' CustomTendToTurn(113456789); // '1.13亿' CustomTendToTurn(-110000000); // '-1.10亿' CustomTendToTurn(11000); // '1.10万' CustomTendToTurn(-11000); // '-1.10万' CustomTendToTurn(11); // '11' */ function CustomTendToTurn(num) { var digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; return CustomTendToNumber(num, digits) + CustomTendToUnit(num); } /** * 转换成万的单位 * @param {number} num 转换成万的数字 * @param {number} digits 保留的小数位数 * @returns {string} 返回转换成万的组合 */ /** CustomTendToTurn(); // '' CustomTendToTurn(113456789); // '11345.68' CustomTendToTurn(-110000000); // '-11000.00' CustomTendToTurn(11000); // '1.10' CustomTendToTurn(-11000); // '-1.10' CustomTendToTurn(11); // '0.00' */ function CustomTendToWan(num) { var digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; if (!CustomIsNumeric(num)) return ''; num = parseFloat(num); var character = num >= 0 ? '' : '-'; // 符号 var shortNum = Math.abs(num); shortNum = CustomNumberToFixed(shortNum / 10000, digits); return character + shortNum; } /** * 千分位分隔符 * @param {number} num 被格式化的数字 * @param {number} decimalPlaces * @returns */ /* console.log(CustomThousandSplit(obj.a)); // "" console.log(CustomThousandSplit(obj.b)); // "" console.log(CustomThousandSplit(1000)); // "1,000" console.log(CustomThousandSplit(-1000)); // "-1,000" console.log(CustomThousandSplit(1234.5678, 2)); // "1,234.57" console.log(CustomThousandSplit(-1234.5678, 2)); // "-1,234.57" console.log(CustomThousandSplit(1234.5678)); // "1,234.5678" console.log(CustomThousandSplit(-1234.5678)); // "-1,234.5678" console.log(CustomThousandSplit(0, 2)); // "0" console.log(CustomThousandSplit(0, 2)); // "0.00" console.log(CustomThousandSplit(0.1234, 4)); // "0.1234" console.log(CustomThousandSplit(-0.1234, 4)); // "-0.1234" console.log(CustomThousandSplit(123456789)); // "123,456,789" console.log(CustomThousandSplit(-123456789)); // "-123,456,789" console.log(CustomThousandSplit(123456789.123456789, 5)); // "123,456,789.12346" console.log(CustomThousandSplit(-123456789.123456789, 5)); // "-123,456,789.12346" console.log(CustomThousandSplit(0.000000001, 9)); // "0.000000001" console.log(CustomThousandSplit(-0.000000001, 9)); // "-0.000000001" console.log(CustomThousandSplit(null)); // "" console.log(CustomThousandSplit(undefined)); // "" console.log(CustomThousandSplit('1000')); // "1,000" console.log(CustomThousandSplit('-1000')); // "-1,000" console.log(CustomThousandSplit('1234.5678', 2)); // "1,234.57" console.log(CustomThousandSplit('-1234.5678', 2)); // "-1,234.57" console.log(CustomThousandSplit('1234.5678')); // "1,234.5678" console.log(CustomThousandSplit('-1234.5678')); // "-1,234.5678" console.log(CustomThousandSplit('0')); // "0" console.log(CustomThousandSplit('0.1234', 4)); // "0.1234" console.log(CustomThousandSplit('-0.1234', 4)); // "-0.1234" console.log(CustomThousandSplit('123456789')); // "123,456,789" console.log(CustomThousandSplit('-123456789')); // "-123,456,789" console.log(CustomThousandSplit('123456789.123456789', 5)); // "123,456,789.12346" console.log(CustomThousandSplit('-123456789.123456789', 5)); // "-123,456,789.12346" console.log(CustomThousandSplit('0.000000001', 9)); // "0.000000001" console.log(CustomThousandSplit('-0.000000001', 9)); // "-0.000000001" */ function CustomThousandSplit(num, decimalPlaces) { if ([null, undefined].includes(num)) { return ''; } num = String(num); var thousandSeparator = ','; var decimalSeparator = '.'; var sign = num[0] === '-' ? '-' : ''; var absNum = Math.abs(parseFloat(num)); var integerPart = Math.floor(absNum).toString().replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator); var decimalPart = decimalPlaces !== undefined ? decimalSeparator + absNum.toFixed(decimalPlaces).split('.')[1] : ''; return sign + integerPart + decimalPart; } // export function numberFormat(num) { // if (isNaN(parseFloat(num)) || parseFloat(num) === Infinity) return ''; // let fixedIndex = // num.toString().indexOf('.') === -1 // ? 0 // : num.toString().split('.')[1].length; // return parseFloat(num) // .toFixed(fixedIndex) // .replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,'); // } function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var arrayWithHoles = createCommonjsModule(function (module) { function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; }); unwrapExports(arrayWithHoles); var iterableToArrayLimit = createCommonjsModule(function (module) { function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports; }); unwrapExports(iterableToArrayLimit); var arrayLikeToArray = createCommonjsModule(function (module) { function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; }); unwrapExports(arrayLikeToArray); var unsupportedIterableToArray = createCommonjsModule(function (module) { function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); } module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; }); unwrapExports(unsupportedIterableToArray); var nonIterableRest = createCommonjsModule(function (module) { function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports; }); unwrapExports(nonIterableRest); var slicedToArray = createCommonjsModule(function (module) { function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); } module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; }); var _slicedToArray = unwrapExports(slicedToArray); /** * 深度克隆函数(包含函数、原型链、数组、循环引用,Symbol、Map、Set等) * @param {*} obj * @param {*} [hash=new WeakMap()] * @return {*} */ /** // 测试一: let obj = { str: 'hello world', num: 123, bool: true, nul: null, und: undefined, arr: [1, 2, 3], obj: { a: 1, b: 2, c: 3 }, func: function () { console.log('hello world'); }, sym: Symbol('hello'), map: new Map([ ['name', 'Tom'], ['age', 18], ]), set: new Set([1, 2, 3]), }; obj.loop = obj; // 循环引用 let cloneObj = CustomDeepClone(obj); console.log(cloneObj); obj.str = 'AIGC'; console.log(cloneObj); cloneObj.str = 'WEBAI'; console.log(cloneObj); console.log(obj); // 测试二: let arr1 = [{ a: 6 }, { a: 7 }]; let arr2 = CustomDeepClone(arr1); arr1[0].a = 8; arr2[0].a = 9; console.log(arr1);// [{ a: 8 }, { a: 7 }] console.log(arr2);// [{ a: 9 }, { a: 7 }] */ function CustomDeepClone(obj) { var hash = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new WeakMap(); if (Object(obj) !== obj || obj instanceof Function || obj instanceof RegExp || obj instanceof Error || obj instanceof Date) { return obj; } if (hash.has(obj)) { return hash.get(obj); } var result; try { result = new obj.constructor(); } catch (e) { result = Object.create(Object.getPrototypeOf(obj)); } hash.set(obj, result); if (obj instanceof Map) { Array.from(obj, function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], val = _ref2[1]; return result.set(deepClone(key, hash), deepClone(val, hash)); }); } else if (obj instanceof Set) { Array.from(obj, function (key) { return result.add(deepClone(key, hash)); }); } else if (Array.isArray(obj)) { result = obj.map(function (item) { return deepClone(item, hash); }); } else { result = Object.getOwnPropertyNames(obj).reduce(function (acc, key) { var descriptor = Object.getOwnPropertyDescriptor(obj, key); if (descriptor.value !== undefined && typeof descriptor.value !== 'function') { descriptor.value = deepClone(descriptor.value, hash); } else if (descriptor.get || descriptor.set) { descriptor.get = deepClone(descriptor.get, hash); descriptor.set = deepClone(descriptor.set, hash); } Object.defineProperty(acc, key, descriptor); return acc; }, result); Object.setPrototypeOf(result, deepClone(Object.getPrototypeOf(obj), hash)); } if (obj instanceof Map) { Object.setPrototypeOf(result, Map.prototype); } else if (obj instanceof Set) { Object.setPrototypeOf(result, Set.prototype); } return result; } /** * 字节转换 * @param {string} limit * @returns {string} */ /** CustomByteConversion(1023); //输出:1023B CustomByteConversion(1024); //输出:1.00KB CustomByteConversion(1024 * 1024); //输出:1.00MB CustomByteConversion(1024 * 1024 * 1024); //输出:1.00GB CustomByteConversion(0.1); //输出:0.10B CustomByteConversion(0.1 * 1024); //输出:0.10KB CustomByteConversion(0.1 * 1024 * 1024); //输出:0.10MB CustomByteConversion(0.1 * 1024 * 1024 * 1024); //输出:0.10GB */ function CustomByteConversion(limit) { var size = ''; if (limit < 0.1 * 1024) { //小于0.1KB,则转化成B size = limit.toFixed(2) + 'B'; } else if (limit < 0.1 * 1024 * 1024) { //小于0.1MB,则转化成KB size = (limit / 1024).toFixed(2) + 'KB'; } else if (limit < 0.1 * 1024 * 1024 * 1024) { //小于0.1GB,则转化成MB size = (limit / (1024 * 1024)).toFixed(2) + 'MB'; } else { //其他转化成GB size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'; } var sizeStr = size + ''; //转成字符串 var index = sizeStr.indexOf('.'); //获取小数点处的索引 var dou = sizeStr.substr(index + 1, 2); //获取小数点后两位的值 if (dou == '00') { //判断后两位是否为00,如果是则删除00 return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2); } return size; } /** * 函数防抖:fn函数在最后一次调用时刻的delay毫秒之后执行! * @param fn 执行函数 * @param delay 时间间隔 * @param isImmediate 为true,debounce会在delay时间间隔的开始时立即调用这个函数 * @returns {Function} */ /* // 测试一: let count = 0; const fn = () => count++; // const debouncedFn = () => fn(); const debouncedFn = CustomDebounce(fn, 500); debouncedFn(); debouncedFn(); debouncedFn(); setTimeout(() => { console.log(count); }, 600); // 测试二: const consoleFn = () => console.log(+new Date()); let testFn = CustomDebounce(consoleFn, 500); let count = 0; let timerSign = setInterval(() => { testFn(); if (count > 30) clearInterval(timerSign); count++; }, 100); */ function CustomDebounce(fn) { var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; var isImmediate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var timer = null; // 初始化timer,作为计时清除依据 return function () { var context = this; // 获取函数所在作用域this var args = arguments; // 取得传入参数 clearTimeout(timer); if (isImmediate && timer === null) { fn.apply(context, args); // 时间间隔外立即执行 timer = 0; return; } timer = setTimeout(function () { fn.apply(context, args); timer = null; }, delay); }; } /* // 测试fn被正常调用 test('CustomDebounce - fn is called once when called multiple times within the delay time', () => { let count = 0; // 模拟重复调用fn函数 const fn = () => count++; // 使用CustomDebounce包装fn函数 const debouncedFn = CustomDebounce(fn, 500); // 调用debouncedFn函数,模拟在500ms内调用了多次 debouncedFn(); debouncedFn(); debouncedFn(); // 延迟510ms后检查count值是否仅增加了一次 return new Promise((resolve) => { setTimeout(() => { expect(count).toBe(1); resolve(); }, 510); }); }); // 测试isImmediate为true时,fn立即执行 test('CustomDebounce - fn is called immediately when isImmediate is true', () => { let count = 0; // 模拟重复调用fn函数 const fn = () => count++; // 使用CustomDebounce包装fn函数,并指定isImmediate为true const debouncedFn = CustomDebounce(fn, 500, true); // 调用debouncedFn函数 debouncedFn(); // 检查count值是否被增加了一次 expect(count).toBe(1); }); // 测试fn能够正常接收参数 test('CustomDebounce - fn can receive arguments', () => { let num = 0; // 模拟重复调用fn函数 const fn = (n) => num += n; // 使用CustomDebounce包装fn函数,并指定delay参数为0 const debouncedFn = CustomDebounce(fn, 0); // 调用debouncedFn函数,并传入一个参数 debouncedFn(5); // 检查num值是否被增加了5 expect(num).toBe(5); }); */ /** * 获取类型(以全小写返回) * @param {*} obj 传入的类型 * @returns {string} 返回字符串类型 */ /** * CustomGetTypeOf(0);// 'number' * CustomGetTypeOf('');// 'string' * CustomGetTypeOf(null);// 'null' * CustomGetTypeOf(undefined);// 'undefined' * CustomGetTypeOf({});// 'object' * CustomGetTypeOf(Symbol(1));// 'symbol' * CustomGetTypeOf(function(){});// 'function' * CustomGetTypeOf([1,2,3]);// 'array' * CustomGetTypeOf(new Date());// 'date' * CustomGetTypeOf(true);// 'boolean' * CustomGetTypeOf(NaN);// 'nan' */ function CustomGetTypeOf(obj) { if (Number.isNaN(obj) && isNaN(obj)) return 'nan'; return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); } // convert #hex notation to rgb array var parseColor = function parseColor(hexStr) { return hexStr.length === 4 ? hexStr.substr(1).split('').map(function (s) { return 0x11 * parseInt(s, 16); }) : [hexStr.substr(1, 2), hexStr.substr(3, 2), hexStr.substr(5, 2)].map(function (s) { return parseInt(s, 16); }); }; var pad = function pad(s) { return s.length === 1 ? '0' + s : s; }; /** * 渐变色数组 * @param {string} start 开始颜色(16进制) * @param {string} end 结束颜色(16进制) * @param {number} steps 分解次数 * @param {number} gamma 透明度 * @returns {array} 颜色的渐变色数组 */ /** CustomGradientColors('#00ff00', '#ff0000', 0); // [] CustomGradientColors('#00ff00', '#ff0000', 1); // ['#00ff00'] CustomGradientColors('#00ff00', '#ff0000', 4); // ['#00ff00', '#55aa00', '#aa5500', '#ff0000'] CustomGradientColors('#000', '#fff', 3, 2.2); // ['#000000', '#bababa', '#ffffff'] */ function CustomGradientColors(start, end, steps, gamma) { if (steps === 0) { return []; } else if (steps === 1) { return [start]; } var i, j, ms, me, output = [], so = []; gamma = gamma || 1; var normalize = function normalize(channel) { return Math.pow(channel / 255, gamma); }; start = parseColor(start).map(normalize); end = parseColor(end).map(normalize); for (i = 0; i < steps; i++) { ms = i / (steps - 1); me = 1 - ms; for (j = 0; j < 3; j++) { so[j] = pad(Math.round(Math.pow(start[j] * me + end[j] * ms, 1 / gamma) * 255).toString(16)); } output.push('#' + so.join('')); } return output; } /** * 密码校验 * 规则:8-12位,包含大小写字母、数字、特殊字符 * @param {string} val * @returns {obj} isTrue:是否通过 message:提示信息 */ /* CustomPasswordVerifiersFn('11111111');// {isTrue:false,message: '...'} CustomPasswordVerifiersFn('Abcde');// {isTrue:false,message: '...'} CustomPasswordVerifiersFn('Abcdefghigklmn');// {isTrue:false,message: '...'} CustomPasswordVerifiersFn('Abcde123');// {isTrue:false,message: '...'} CustomPasswordVerifiersFn('Abcdefg!');// {isTrue:false,message: '...'} CustomPasswordVerifiersFn('abcdefg1!');// {isTrue:false,message: '...'} CustomPasswordVerifiersFn('Abcde12!');// {isTrue:true,message: '验证通过'} */ function CustomPasswordVerifiersFn(val) { var valArr = val.split(''); var illegalStr = []; // 非法字符有哪些 var verification1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var verification2 = "abcdefghijklmnopqrstuvwxyz"; var verification3 = "0123456789"; var verification4 = "!@#$&*."; var verificatType1 = []; // 大写字母收集 var verificatType2 = []; // 小写字母收集 var verificatType3 = []; // 数字类型收集 var verificatType4 = []; // 特殊字母收集 var verificationStr = verification1.concat(verification2).concat(verification3).concat(verification4); valArr.forEach(function (item) { if (verificationStr.includes(item)) { if (verification1.includes(item)) { verificatType1.push(item); } else if (verification2.includes(item)) { verificatType2.push(item); } else if (verification3.includes(item)) { verificatType3.push(item); } else if (verification4.includes(item)) { verificatType4.push(item); } } else { illegalStr.push(item); } }); var signArr = []; valArr.length < 8 && signArr.push('密码长度小于8位'); valArr.length > 12 && signArr.push('密码长度大于12位'); !verificatType1.length && signArr.push('未包含大写字母'); !verificatType2.length && signArr.push('未包含小写字母'); !verificatType3.length && signArr.push('未包含数字'); !verificatType4.length && signArr.push('未包含特殊符号'); illegalStr.length && signArr.push("\u5305\u542B\u672A\u6307\u5B9A\u5B57\u7B26\uFF1A".concat(signArr.join(''))); if (signArr.length) { signArr.unshift('密码校验存在以下问题:'); signArr.push(''); signArr.push('温馨提示:'); signArr.push('密码规则:8-12位,包含大小写字母、数字、特殊符号'); signArr.push("\u5927\u5199\u5B57\u6BCD\u53D6\u503C\u8303\u56F4\uFF1A".concat(verification1)); signArr.push("\u5C0F\u5199\u5B57\u6BCD\u53D6\u503C\u8303\u56F4\uFF1A".concat(verification2)); signArr.push("\u6570\u5B57\u53D6\u503C\u8303\u56F4\uFF1A".concat(verification3)); signArr.push("\u7279\u6B8A\u7B26\u53F7\u53D6\u503C\u8303\u56F4\uFF1A".concat(verification4)); return { isTrue: false, message: signArr.join('\n') }; } else { return { isTrue: true, message: '验证通过' }; } } /** * 自定义节流函数 * @param {Function} func - 需要节流的函数 * @param {number} delay - 节流时间间隔 * @returns {Function} - 节流后的函数 */ /** function testThrottle() { function printTime() { console.log(new Date().getTime()); } const throttledPrintTime = CustomThrottle(printTime, 1000); setInterval(throttledPrintTime, 100); } testThrottle(); */ function CustomThrottle(func, delay) { var last = 0; return function () { var now = new Date().getTime(); if (now - last < delay) { return; } last = now; func.apply(void 0, arguments); }; } /** * 获取地址栏参数 * @param {string} name 获取的字段 * @returns {string} 参数信息 */ /** https://www.baidu.com/s?wd=boxue url CustomUrlParam('wd');// boxue CustomUrlParam('id');// null */ function CustomUrlParam(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r != null) return unescape(r[2]); return null; //返回参数值 } /** * 验证邮箱 * @param {string} email * @returns */ /** validateEmail('example@mail.com'); // true validateEmail('example@mail'); // false validateEmail('example@mail.'); // false validateEmail('example@mail..com'); // false validateEmail('example@mail.com '); // false validateEmail(' example@mail.com'); // false */ function CustomValidateEmail(email) { var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } /** * 验证手机号 * @param {string} phoneNumber * @returns */ /** CustomValidatePhone('13912345678');// true CustomValidatePhone('18888888888');// true CustomValidatePhone('13567891234');// true CustomValidatePhone('12345678901');// false CustomValidatePhone('2345678901');// false CustomValidatePhone('1391234567');// false */ function CustomValidatePhone(phoneNumber) { var regex = /^1[3456789]\d{9}$/; return regex.test(phoneNumber); } var _typeof_1 = createCommonjsModule(function (module) { function _typeof(obj) { "@babel/helpers - typeof"; return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj); } module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; }); var _typeof = unwrapExports(_typeof_1); /** * 网页添加水印 */ /** CustomWatermark('张三') CustomWatermark({ waterText: '张三', // 水印文字 positionTop: '100px', positionleft: '100px', }); let watermark = new CustomWatermark('医保支付'); watermark.destroyed();// 销毁 */ //声明 var watermark = {}; //水印配置 var setWatermark = function setWatermark(params) { // 水印参数 var watermarkParameters = { waterText: '', // 水印文字 waterTextColor: '#EBEBEB', // 水印文字颜色 waterTextFontSize: 20, // number,水印文字大小 waterElID: 'CustomWater-' + '1.23452384164.123412415', // 水印挂载的id,【需以CustomWater-开头】 waterAreaWidth: document.documentElement.clientWidth, // number,水印区域宽度 waterAreaHeight: document.documentElement.clientHeight, // number,水印区域高度 waterAreaPosition: 'fixed', waterAreazIndex: '9999999', waterMountElement: document.body, waterAreaOpacity: 0.2, waterAreaRotate: -20 * Math.PI / 150, // 水印的旋转角度 singleWidth: 200, // 需大于文字的宽度 singleHeight: 200, // 需大于文字所需要的高度 positionTop: '0px', positionleft: '0px' }; if (typeof params === 'string') { watermarkParameters.waterText = params; } else if (_typeof(params) === 'object') { watermarkParameters = Object.assign({}, watermarkParameters, params); } else { return false; } var CanvasID = watermarkParameters.waterElID; if (!CanvasID.startsWith('CustomWater')) { CanvasID = 'CustomWater-' + CanvasID; } // 移除旧水印 if (document.getElementById(CanvasID) !== null) { document.body.removeChild(document.getElementById(CanvasID)); } //创建画布 var createCanvas = document.createElement('canvas'); // 设置canvas画布大小 var actualNeedsWdith = 20 * watermarkParameters.waterText.length; watermarkParameters.singleWidth = Math.max(watermarkParameters.singleWidth, actualNeedsWdith); var actualNeedsHeight = 18 * watermarkParameters.waterText.length; watermarkParameters.singleHeight = Math.max(watermarkParameters.singleHeight, actualNeedsHeight); createCanvas.width = watermarkParameters.singleWidth; //宽度 createCanvas.height = watermarkParameters.singleHeight; //高度 //创建Context2D对象作为2D渲染的上下文。 var Context2D = createCanvas.getContext('2d'); /*水印样式调整配置*/ Context2D.rotate(watermarkParameters.waterAreaRotate); // 水印旋转角度 Context2D.fillStyle = watermarkParameters.waterTextColor; //浅色模式或后台 Context2D.font = watermarkParameters.waterTextFontSize + 'px Vedana'; //水印文字大小 Context2D.textAlign = 'center'; //水印水平位置 Context2D.textBaseline = 'alphabetic'; //水印垂直位置 Context2D.fillText(watermarkParameters.waterText, createCanvas.width / 3, createCanvas.height / 2); //创建元素 var createDiv = document.createElement('div'); createDiv.id = CanvasID; //水印默认设置 createDiv.style.opacity = watermarkParameters.waterAreaOpacity; createDiv.style.pointerEvents = 'none'; //水印层事件穿透 让水印不阻止交互事件 createDiv.style.top = watermarkParameters.positionTop; //水印顶部距离 createDiv.style.left = watermarkParameters.positionleft; //水印左侧距离 createDiv.style.position = watermarkParameters.waterAreaPosition; //水印定位 createDiv.style.zIndex = watermarkParameters.waterAreazIndex; //水印样式优先显示 createDiv.style.width = watermarkParameters.waterAreaWidth + 'px'; //水印宽度 createDiv.style.height = watermarkParameters.waterAreaHeight + 'px'; //水印高度 createDiv.style.background = 'url(' + createCanvas.toDataURL('image/png') + ') left top repeat'; //水印显示(关键代码) watermarkParameters.waterMountElement.appendChild(createDiv); //在指定元素节点的最后一个子节点之后添加节点 return CanvasID; }; // function resizeHandler() { // setWatermark(params); // } // 此方法只允许调用一次 watermark.set = function (params) { var id = setWatermark(params); //设置间隔 var timer = setInterval(function () { if (document.getElementById(id) === null) { id = setWatermark(params); } else { clearTimeout(timer); } }, 500); //改变大小时执行 window.onresize = function () { setWatermark(params); }; // window.addEventListener('resize', resizeHandler); }; function CustomWatermark(params) { watermark.set(params); } // 移除销毁元素 CustomWatermark.prototype.destroyed = function () { var CustomWaterEls = document.querySelectorAll('[id^="CustomWater-"]'); for (var i = 0; i < CustomWaterEls.length; i++) { CustomWaterEls[i].remove(); } // window.removeEventListener('resize', resizeHandler); }; /** * 判断一个数组是否是正序的二维数组 * @param {*} arr * @returns {boolean} */ function IsAscendingOrderArr() { var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; if (!arr.length) return false; var flag = true; arr.forEach(function (item) { var flag_01 = CustomGetTypeOf(item[0]) === 'number'; var flag_02 = CustomGetTypeOf(item[1]) === 'number'; var flag_03 = Number.isInteger(item[0]) && item[0] > -1; var flag_04 = Number.isInteger(item[1]) && item[1] > -1; var flag_05 = item[0] <= item[1]; if (!(flag_01 && flag_02 && flag_03 && flag_04 && flag_05)) { flag = false; } }); return flag; } /** * 判断是否一维数字数组 * @param {array} arr * @returns {boolean} */ function OnedimensionalNumberArray() { var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; if (!arr.length) return false; var flag = true; arr.forEach(function (item) { var flag_01 = CustomGetTypeOf(item) === 'number'; var flag_02 = Number.isInteger(item); // 判断是否是整数 var flag_03 = item > -1; if (!(flag_01 && flag_02 && flag_03)) { flag = false; } }); return flag; } /** * 字符串处理的通用函数 * @param {string} processStr -- 传入的字符串 * @param {number,array} param_1 * @param {nunber,string} param_2 * @param {nunber} param_3 * @returns {string} */ /* // 动态替换索引位置的字符 CustomHideStrGeneral('abcdefghijklmn',[0,1,4,5,6],'x');// '$$cd$$$hijklmn' // 替换连续位置的字符 CustomHideStrGeneral('abcdefghijklmn',1,5,'x');// 'a$$$$$ghijklmn' // 替换分段索引位置的字符 CustomHideStrGeneral('abcdefghijklmn',[[0,2],[4,6]],'x');// '$$$d$$$hijklmn' */ function CustomHideStrGeneral() { var processStr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var param_1 = arguments.length > 1 ? arguments[1] : undefined; var param_2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '*'; var param_3 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '*'; try { if (CustomGetTypeOf(processStr) !== 'string') { throw new Error('请传入字符串'); } if (!processStr.length) { return processStr; } if (CustomGetTypeOf(param_1) === 'array') { if (OnedimensionalNumberArray(param_1)) { // 纯一维数字数组 return processStr.split('').reduce(function (prev, item, index) { return prev += param_1.includes(index) ? param_2 : item; }, ''); } else if (IsAscendingOrderArr(param_1)) { // 纯二维数字数组 param_1.forEach(function (item_01) { processStr = processStr.split('').reduce(function (prev, item_02, index) { return prev += item_01[0] <= index && index <= item_01[1] ? param_2 : item_02; }, ''); }); return processStr; } else { throw new Error('请检查数组格式'); } } else if (CustomGetTypeOf(param_1) === 'number') { var flag_01 = Number.isInteger(param_1); // 判断是否是整数 var flag_02 = Number.isInteger(param_2); // 判断是否是整数 if (CustomGetTypeOf(param_2) === 'number' && flag_01 && flag_02) { if (param_1 > param_2) { throw new Error('字符串截取开始位置不能大于结束位置'); } param_1 = param_1 > 0 ? param_1 : 0; param_2 = param_2 > processStr.length ? processStr.length : param_2; return processStr.split('').reduce(function (prev, item, index) { return prev += param_1 <= index && index <= param_2 ? param_3 : item; }, ''); } else { throw new Error('第二个参数、第三个参数需为非负整数'); } } else { return processStr; } } catch (err) { console.log(err); } } /** * 姓名脱敏 * 规则:整体保持前一后一,其它隐藏 * @param {string} nameStr 传入的姓名 * @param {string} character 要替换的字符,默认是* * @returns {string} 返回替换后的姓名 */ /** let obj = { a: null, b: undefined }; CustomPer