JavaScript常用工具函数大全
程序员文章站
2024-01-10 15:11:28
...
- Set的简单实现
function set(v) {
function unique(arr) {
let ret = [];
let obj = {};
arr.forEach(item => {
if(!obj[item]) {
obj[item] = true;
ret.push(item);
}
});
return ret;
}
function SetRe(arr) {
this.items = arr ? unique(arr) : [];
this.size = arr.length;
}
SetRe.prototype = {
has: function(v) {
return this.items.some(item => item === v);
},
add: function(v) {
this.items.push(v);
this.size++;
},
remote: function(v) {
return this.items.some((item, index) => {
if(item === v) {
this.items.splice(index, 1);
this.size = 0;
return true;
}
return false;
})
},
clear: function() {
this.items = [];
this.size = 0;
},
getValues: function() {
return this.items
}
}
}
- 生成一个重复的字符串,有n个str组成,可修改为填充为数组等 OR str.repeat(次数2)
function repeat(str, n) {
let res = '';
while(n) {
if(n % 2 === 1) {
res += str;
}
if(n > 1) {
str += str;
}
n >>= 1;
}
return res;
}
- 格式化时间
function dateFormater(formater, t) {
let date = t ? new Date(t) : new Date(),
Y = date.getFullYear() + '',
M = date.getMonth() + 1,
D = date.getDate(),
H = date.getHours(),
m = date.getMinutes(),
s = date.getSeconds();
return formater.replace(/YYYY|yyyy/g, Y)
.replace(/YY|yy/g, Y.substr(2,2))
.replace(/MM/g, (M<10?'0':'') + M)
.replace(/DD/g, (D<10?'0':'') + D)
.replace(/HH|hh/g,(H<10?'0':'') + H)
.replace(/mm/g,(m<10?'0':'') + m)
.replace(/ss/g,(s<10?'0':'') + s)
}
- 将指定字符串由一种时间格式转化为另一种
function dateStrForma(str, from, to) {
str += '';
let Y = '';
if((Y = from.indexOf('YYYY')) >= 0){
Y = str.substr(Y, 4);
to = to.replace(/YYYY|yyyy/g, Y);
} else if((Y = from.indexOf('YY')) >= 0) {
Y = str.substr(Y, 2);
to = to.replace(/YY|yy/g, Y);
}
let k,i;
['M','D','H','h','m','s'].forEach(s => {
i = from.indexOf(s+s);
k = ~i ? str.substr(i, 2) : '';
to = to.replace(s+s, k);
});
return to;
- 根据字符串路径获取对象属性 : ‘obj[0].count’
function getPropByPath(obj, path, strict) {
let tempObj = obj;
path = path.replace(/[(\w+)]/g, '.$1'); //将[0]转化为.0
path = path.replace(/^\./, ''); //去除开头的.
let keyArr = path.split('.'); //根据.切割
let i = 0;
for(let len = keyArr.length; i < len - 1; ++i) {
if (!tempObj && !strict) break;
let key = keyArr[i];
if (key in tempObj) {
tempObj = tempObj[key];
} else {
if (strict) {//开启严格模式,没找到对应key值,抛出错误
throw new Error('please transfer a valid prop path to form item!');
}
break;
}
}
return {
o: tempObj, //原始数据
k: keyArr[i], //key值
v: tempObj ? tempObj[keyArr[i]] : null // key值对应的值
};
}
- 检测数据是不是基本数据类型
function isStatic(v) {
return(
typeof v === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'undefined' ||
typeof value === 'symbol'
)
}
- 判断数据是不是引用数据类型
function isObject(v) {
let type = typeof v;
return v !== null && (type == 'object' || type == 'function');
}
- 判断数据是不是数组
function isArray(v) {
return (
v instanceof Array ||
Array.isArray(v) ||
Object.prototype.toString.call(v) === '[object Array]'
)
}
- 检测数据是什么类型
function isType(value) {
let type = Object.prototype.toString.call(value);
switch (type) {
case "[object String]":
return "字符串";
case "[object Number]":
return "数字";
case "[object Boolean]":
return "布尔";
case "[object Function]":
return "函数";
case "[object Array]":
return "数组";
case "[object Object]":
return "对象";
case "[object Date]":
return "日期";
case "[object RegExp]":
return "正则";
case "[object Math]":
return "数学对象";
case "[object Undefined]":
return "未定义";
case "[object Null]":
return "空";
}
}
- 返回 值的类型
function getRawType(v) {
return Object.prototype.toString.call(v).slice(8, -1);
}
- 判断是否为浏览器内置函数 内置函数toString后的主体代码块为 [native code] ,而非内置函数则为相关代码
function isNative(v) {
return typeof v === 'function' && (/native code/.test(v.tiString()));
}
- 判断是否为null
function isEmpty(v) {
if(v == null) return null;
if(Object.prototype.toString.call(value) === '[object Array]') return v.length;
if(Object.prototype.toString.call(value) === '[object Object]') {
for(let k in v) {
if(v.hasOwnProperty(k)) return false;
}
}
}
- 检查数据是否是非数字值
function _isNaN(v){
return !(typeof v === 'string' || typeof v === 'number') || isNaN(v)
}
- 求取数组中最大值 最小值
function maxOrMin(arr){
arr.sort(function (a, b) {
return a-b; //return < 0 a在b之前 > 0 b在a之前
});
Math.max(arr);
Math.min(arr);
return arr[arr.length-1];
}
- 返回一个lower - upper之间的随机数
function random(lower, upper){
lower = +lower || 0
upper = +upper || 0
return Math.random() * (upper - lower) + lower;
}
- 禁止某些键盘事件
function keydown() {
document.addEventListener('keydown', function(event){
return !(
112 == event.keyCode || //F1
123 == event.keyCode || //F12
event.ctrlKey && 82 == event.keyCode || //ctrl + R
event.ctrlKey && 78 == event.keyCode || //ctrl + N
event.shiftKey && 121 == event.keyCode || //shift + F10
event.altKey && 115 == event.keyCode || //alt + F4
"A" == event.srcElement.tagName && event.shiftKey //shift + 点击a标签
) || (event.returnValue = false)
});
}
- 禁止右键、选择、复制
function csc() {
['contextmenu', 'selectstart', 'copy'].forEach(function(ev){
document.addEventListener(ev, function(event){
return event.returnValue = false
})
});
}
- 记忆函数:通过闭包缓存函数的运算结果
function cached(fn) {
let cache = Object.create(null);
return function(str) {
let hit = cache[str];
return hit || (cache[str] = fn(str));
}
}
- _命名替换为驼峰命名
function camelize(str) {
return str.replace(/_(\w)/g, function(z, a, b) {
return a ? a.toUpperCase() : '';
})
}
- 驼峰命名转_命名
function hump(v) {
return v.replace(/\B[A-Z]/g, function(z) {
return z ? '_' + z.toLowerCase() : '';
}); ||
return v.replace(/\B([A-Z])/g, '_$1').toLowerCase();
}
- 字符串首位大写
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
- 将属性混合到目标对象中
function extend(to, _from) {
for(let key in _from) {
to[key] = _from[key];
}
return to
}
- 识别各种浏览器及平台 Navigator
function getBrowser() {
let inBrowser = typeof window !== 'undefined'; //运行环境是浏览器
//运行环境是微信
let inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
let weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
//浏览器 UA 判断
let UA = inBrowser && window.navigator.userAgent.toLowerCase();
let isIE = UA && /msie|trident/.test(UA);
let isIE9 = UA && UA.indexOf('msie 9.0') > 0;
let isEdge = UA && UA.indexOf('edge/') > 0;
let isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');
let isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');
let isChrome = UA && /chrome\d+/.test(UA) && !isEdge;
}
- 获取浏览器信息
function getExplorerInfo() {
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("msie") ? { //ie < 11
type: "IE",
version: Number(t.match(/msie\/([d]+)/)[1])
} : !!t.match(/trident\.+?rv:(([d.]+))/) ? { // ie 11
type: "IE",
version: 11
} : 0 <= t.indexOf("edge") ? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1])
} : 0 <= t.indexOf("firefox") ? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1])
} : 0 <= t.indexOf("chrome") ? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d]+)/)[1])
} : 0 <= t.indexOf("opera") ? {
type: "Opera",
version: Number(t.match(/opera\.([\d]+)/)[1])
} : 0 <= t.indexOf("Safari") ? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1])
} : {
type: t,
version: -1
}
}
- 检测是否为PC端浏览器模式
function isPCBroswer() {
let e = navigator.userAgent.toLowerCase()
, t = "ipad" == e.match(/ipad/i)
, i = "iphone" == e.match(/iphone/i)
, r = "midp" == e.match(/midp/i)
, n = "rv:1.2.3.4" == e.match(/rv:1.2.3.4/i)
, a = "ucweb" == e.match(/ucweb/i)
, o = "android" == e.match(/android/i)
, s = "windows ce" == e.match(/windows ce/i)
, l = "windows mobile" == e.match(/windows mobile/i);
return !(t || i || r || n || a || o || s || l)
}
- 获取Url参数,返回一个对象
function GetUrlParam(url) {
url = url ? url : document.location.toString();
let arrObj = url.split('?');
let params = Object.create(null);
if(arrObj.length > 1) {
arrObj = arrObj[1].split("&");
arrObj.forEach(item => {
item = item.split('=');
params[item[0]] = item[1];
})
}
return params;
}
- 按“F11”
function isFullscreenForNoScroll(){
let explorer = window.navigator.userAgent.toLowerCase();
if(explorer.indexOf('chrome')>0){//webkit
if (document.body.scrollHeight === window.screen.height && document.body.scrollWidth === window.screen.width) {
alert("全屏");
} else {
alert("不全屏");
}
}else{//IE 9+ fireFox
if (window.outerHeight === window.screen.height && window.outerWidth === window.screen.width) {
alert("全屏");
} else {
alert("不全屏");
}
}
}
- 退出全屏
function exitFullscreen(){
let elem = parent.document;
elem.webkitCancelFullScreen
? elem.webkitCancelFullScreen()
: elem.mozCancelFullScreen
? elem.mozCancelFullScreen()
: elem.cancelFullScreen
? elem.cancelFullScreen()
: elem.msExitFullscreen
? elem.msExitFullscreen()
: elem.exitFullscreen
? elem.exitFullscreen()
: alert("切换失败,可尝试Esc退出");
}