今天给朋友们带来48个JS开发时常用的工具函数。
function isStatic(value) {
return (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'undefined' ||
value === null
)
}
function isPrimitive(value) {
return isStatic(value) || typeof value === 'symbol'
}
function isObject(value) {
let type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
function getRawType(value) {
return Object.prototype.toString.call(value).slice(8, -1)
}
// getoRawType([]) ⇒ Array
function isPlainObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
function isArray(arr) {
return Object.prototype.toString.call(arr) === '[object Array]'
}
// 将isArray挂载到Array上
Array.isArray = Array.isArray || isArray;
function isRegExp(value) {
return Object.prototype.toString.call(value) === '[object RegExp]'
}
function isDate(value) {
return Object.prototype.toString.call(value) === '[object Date]'
}
function isNative(value) {
return typeof value === 'function' && /native code/.test(value.toString())
}
function isFunction(value) {
return Object.prototype.toString.call(value) === '[object Function]'
}
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= Number.MAX_SAFE_INTEGER;
}
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value)) {
return !value.length;
} else if (isPlainObject(value)) {
for (let key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
}
return false;
}
function cached(fn) {
let cache = Object.create(null);
return function cachedFn(str) {
let hit = cache[str];
return hit || (cache[str] = fn(str))
}
}
let camelizeRE = /-(\w)/g;
function camelize(str) {
return str.replace(camelizeRE, function(_, c) {
return c ? c.toUpperCase() : '';
})
}
//ab-cd-ef ==> abCdEf
//使用记忆函数
let _camelize = cached(camelize)
let hyphenateRE = /\B([A-Z])/g;
function hyphenate(str){
return str.replace(hyphenateRE, '-$1').toLowerCase()
}
//abCd ==> ab-cd
//使用记忆函数
let _hyphenate = cached(hyphenate);
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
// abc ==> Abc
//使用记忆函数
let _capitalize = cached(capitalize)
function extend(to, _form) {
for(let key in _form) {
to[key] = _form[key];
}
return to
}
Object.assign = Object.assign || function() {
if (arguments.length == 0) throw new TypeError('Cannot convert undefined or null to object');
let target = arguments[0],
args = Array.prototype.slice.call(arguments, 1),
key;
args.forEach(function(item) {
for (key in item) {
item.hasOwnProperty(key) && (target[key] = item[key])
}
})
return target
}
使用Object.assign可以钱克隆一个对象:
let clone = Object.assign({}, target);
简单的深克隆可以使用JSON.parse()和JSON.stringify(),这两个api是解析json数据的,所以只能解析除symbol外的原始类型及数组和对象。
let clone = JSON.parse( JSON.stringify(target) )
function clone(value, deep) {
if (isPrimitive(value)) {
return value
}
if (isArrayLike(value)) { //是类数组
value = Array.prototype.slice.call(vall)
return value.map(item => deep ? clone(item, deep) : item)
} else if (isPlainObject(value)) { //是对象
let target = {}, key;
for (key in value) {
value.hasOwnProperty(key) && ( target[key] = deep ? clone(value[key], value[key] ))
}
}
let type = getRawType(value);
switch(type) {
case 'Date':
case 'RegExp':
case 'Error': value = new window[type](value); break;
}
return value
}
//运行环境是浏览器
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
}
}
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)
}
下一篇:JS开发常用工具函数(下)https://blog.csdn.net/weixin_43606158/article/details/94660402
这周末此博客将设置权限,非博主粉丝将无法看到。