Content provider: Jinniu District Wudi Software Development Studio

Today, I bring 48 JS development tools to my friends.

  1. IsStatic: Checks whether the data is the original data other than symbol.
function isStatic(value) {
	return (
		typeof value === 'string' ||
		typeof value === 'number' ||
		typeof value === 'boolean' ||
		typeof value === 'undefined' ||
		value === null)}Copy the code
  1. IsPrimitive: Check if the data is raw
function isPrimitive(value) {
	return isStatic(value) || typeof value === 'symbol'
}
Copy the code
  1. IsObject: whether the data is a reference type data (for example, array, function, object, regexe, new Number (), the new String ())
function isObject(value) {
	let type = typeof value;
	returnvalue ! =null && (type == 'object' || type == 'function');
}
Copy the code
  1. IsObjectLike: Checks whether value is a class object. If a value is a class object, it should not be null, and the result after typeof is “object”.
function isObjectLike(value) {
	returnvalue ! =null && typeof value == 'object';
}
Copy the code
  1. GetRawType: gets the data type. The result can be Number, String, Object, or Array
function getRawType(value) {
	return Object.prototype.toString.call(value).slice(8, -1)}/ / getoRawType ([]) ⇒ Array
Copy the code
  1. IsPlainObject: Determines whether data is of type Object
function isPlainObject(obj) {
	return Object.prototype.toString.call(obj) === '[object Object]'
}
Copy the code
  1. IsArray: determines whether the data is an Array (array. isArray).
function isArray(arr) {
	return Object.prototype.toString.call(arr) === '[object Array]'
}

// Mount isArray to Array
Array.isArray = Array.isArray || isArray;
Copy the code
  1. IsRegExp: checks whether data is a regular object
function isRegExp(value) {
	return Object.prototype.toString.call(value) === '[object RegExp]'
}
Copy the code
  1. IsDate: checks whether the data is a time object
function isDate(value) {
    return Object.prototype.toString.call(value) === '[object Date]'
}
Copy the code
  1. IsNative: Determines whether value is a built-in browser function

The main code block after the built-in Function toString is [native code], while non-built-in functions are related code, so non-built-in functions can be copied.

function isNative(value) {
	return typeof value === 'function' && /native code/.test(value.toString())
}
Copy the code
  1. IsFunction: checks whether value is a function
function isFunction(value) {
	return Object.prototype.toString.call(value) === '[object Function]'
}
Copy the code
  1. IsLength: Checks if value is a valid class array length
function isLength(value) {
	return typeof value == 'number' && value > -1 && value % 1= =0 && value <= Number.MAX_SAFE_INTEGER;
}
Copy the code
  1. IsArrayLike: Checks whether a value is a class array

If a value is considered an array of classes, it is not a function, and value.length is an integer greater than or equal to 0 and less than or equal to number. MAX_SAFE_INTEGER. Here strings are also treated as arrays of classes.

function isArrayLike(value) {
	returnvalue ! =null&& isLength(value.length) && ! isFunction(value); }Copy the code
  1. IsEmpty: checks whether the value isEmpty

If null, return true; If it is a class array, determine the length of the data; If the Object is an Object, check whether it has attributes. For other data, return false (or return true instead)

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;
}
Copy the code
  1. Cached: Memory function: cached result of operation
function cached(fn) {
	let cache = Object.create(null);
	return function cachedFn(str) {
		let hit = cache[str];
		return hit || (cache[str] = fn(str))
	}
}
Copy the code
  1. Camelize: naming of horizontal turning hump
let camelizeRE = /-(\w)/g;
function camelize(str) {
	return str.replace(camelizeRE, function(_, c) {
		return c ? c.toUpperCase() : ' '; })}//ab-cd-ef ==> abCdEf
// Use the memory function
let _camelize = cached(camelize)
Copy the code
  1. Hyphenate: Split string, concatenated with -, and converted to lowercase
let hyphenateRE = /\B([A-Z])/g;
function hyphenate(str){
    return str.replace(hyphenateRE, '- $1').toLowerCase()
}
//abCd ==> ab-cd
// Use the memory function
let _hyphenate = cached(hyphenate);
Copy the code
  1. Capitalize: Capitalize the first part of a string
function capitalize(str) {
	return str.charAt(0).toUpperCase() + str.slice(1)}// abc ==> Abc
// Use the memory function
let _capitalize = cached(capitalize)
Copy the code
  1. Extend: Blends properties into the target object
function extend(to, _form) {
	for(let key in _form) {
		to[key] = _form[key];
	}
	return to
}
Copy the code
  1. Object.assign: copy Object attributes, shallow copy
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
}
Copy the code

You can clone an Object using object. assign:

let clone = Object.assign({}, target);
Copy the code

A simple deep clone can use json.parse () and json.stringify (). These apis parse JSON data, so only primitive types and arrays and objects other than Symbol can be parsed.

let clone = JSON.parse( JSON.stringify(target) )
Copy the code
  1. Clone: Clone data, which can be deeply cloned

Cloning rules for primitive types, time, re, error, array, and object are listed here, and the rest is optional

function clone(value, deep) {
	if (isPrimitive(value)) {
		return value
	}
	if (isArrayLike(value)) {  // Is an array of classes
		value = Array.prototype.slice.call(vall)
		return value.map(item= > deep ? clone(item, deep) : item)
	} else if (isPlainObject(value)) {  / / object
		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
}
Copy the code
  1. Identify various browsers and platforms

// The runtime environment is a browser
let inBrowser = typeof window! = ='undefined';
// The operating environment is wechat
let inWeex = typeofWXEnvironment ! = ='undefined'&&!!!!! WXEnvironment.platform;let weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
// Browser UA judgment
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;Copy the code
  1. GetExplorerInfo: Get browser information

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}}Copy the code
  1. IsPCBroswer: Checks whether the browser mode isPC

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: 2. / 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) }Copy the code

JS development common tools and functions (middle)