search
HomeWeb Front-endJS TutorialSummary of JS functions commonly used in front-end development (1)

今天为大家整理了48个JS开发中常用的工具函数。

1、isStatic: 检测数据是不是除了symbol外的原始数据。

function isStatic(value) {
	return (
		typeof value === 'string' ||
		typeof value === 'number' ||
		typeof value === 'boolean' ||
		typeof value === 'undefined' ||
		value === null
	)
}

2、isPrimitive:检测数据是不是原始数据

function isPrimitive(value) {
	return isStatic(value) || typeof value === 'symbol'
}

3、isObject:判断数据是不是引用类型的数据(例如:array,function,object,regexe,new Number(),new String())

function isObject(value) {
	let type = typeof value;
	return value != null && (type == 'object' || type == 'function');
}

4、isObjectLike:检查value是否是类对象。如果一个值是类对象,那么它不应该是null,而且typeof后的结果是“object”。

function isObjectLike(value) {
	return value != null && typeof value == 'object';
}

5、getRawType:获取数据类型,返回结果为Number、String、Object、Array等

function getRawType(value) {
	return Object.prototype.toString.call(value).slice(8, -1)
}
// getoRawType([]) ⇒ Array

6、isPlainObject:判断数据是不是Object类型的数据

function isPlainObject(obj) {
	return Object.prototype.toString.call(obj) === '[object Object]'
}

7、isArray:判断数据是不是数组类型的数据(Array.isArray的兼容写法)

function isArray(arr) {
	return Object.prototype.toString.call(arr) === '[object Array]'
}

// 将isArray挂载到Array上
Array.isArray = Array.isArray || isArray;

8、isRegExp:判断数据是不是正则对象

function isRegExp(value) {
	return Object.prototype.toString.call(value) === '[object RegExp]'
}

9、isDate:判断数据是不是时间对象

function isDate(value) {
    return Object.prototype.toString.call(value) === '[object Date]'
}

10、isNative:判断value是不是浏览器内置函数
内置函数toString后的主体代码块为[native code] ,而非内置函数则为相关代码,所以非内置函数可以进行拷贝(toString后掐头去尾再由Function转)

function isNative(value) {
	return typeof value === 'function' && /native code/.test(value.toString())
}

11、isFunction:检查value是不是函数

function isFunction(value) {
	return Object.prototype.toString.call(value) === '[object Function]'
}

12、isLength:检查value是否为有效的类数组长度

function isLength(value) {
	return typeof value == &#39;number&#39; && value > -1 && value % 1 == 0 && value <= Number.MAX_SAFE_INTEGER;
}

13、isArrayLike:检查value是否是类数组
如果一个值被认为是类数组,那么它不是一个函数,并且value.length是个整数,大于等于0,小于或等于Number.MAX_SAFE_INTEGER。这里字符串也被当作类数组。

function isArrayLike(value) {
	return value != null && isLength(value.length) && !isFunction(value);
}

14、isEmpty:检查value是否为空
如果是null,直接返回true;如果是类数组,判断数据长度;如果是Object对象,判断是否具有属性;如果是其他数据,直接返回false(也可以改为返回true)

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;
}

15、cached:记忆函数:缓存函数的运算结果

function cached(fn) {
	let cache = Object.create(null);
	return function cachedFn(str) {
		let hit = cache[str];
		return hit || (cache[str] = fn(str))
	}
}

16、camelize:横线转驼峰命名

let camelizeRE = /-(\w)/g;
function camelize(str) {
	return str.replace(camelizeRE, function(_, c) {
		return c ? c.toUpperCase() : &#39;&#39;;
	})
}
//ab-cd-ef ==> abCdEf
//使用记忆函数
let _camelize = cached(camelize)

17、hyphenate:驼峰命名转横线命名:拆分字符串,使用-相连,并且转换为小写

let hyphenateRE = /\B([A-Z])/g;
function hyphenate(str){
    return str.replace(hyphenateRE, &#39;-$1&#39;).toLowerCase()
}
//abCd ==> ab-cd
//使用记忆函数
let _hyphenate = cached(hyphenate);

18、capitalize:字符串首位大写

function capitalize(str) {
	return str.charAt(0).toUpperCase() + str.slice(1)
}
// abc ==> Abc
//使用记忆函数
let _capitalize = cached(capitalize)

19、extend:将属性混合到目标对象中

function extend(to, _form) {
	for(let key in _form) {
		to[key] = _form[key];
	}
	return to
}

20、Object.assign:对象属性复制,浅拷贝

Object.assign = Object.assign || function() {
	if (arguments.length == 0) throw new TypeError(&#39;Cannot convert undefined or null to object&#39;);
	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) )

21、clone:克隆数据,可深度克隆
这里列出了原始类型,时间、正则、错误、数组、对象的克隆规则,其他的可自行补充

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 &#39;Date&#39;:
		case &#39;RegExp&#39;:
		case &#39;Error&#39;: value = new window[type](value); break;
	}
	return value
}

22、识别各种浏览器及平台

//运行环境是浏览器
let inBrowser = typeof window !== &#39;undefined&#39;;
//运行环境是微信
let inWeex = typeof WXEnvironment !== &#39;undefined&#39; && !!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(&#39;msie 9.0&#39;) > 0;
let isEdge = UA && UA.indexOf(&#39;edge/&#39;) > 0;
let isAndroid = (UA && UA.indexOf(&#39;android&#39;) > 0) || (weexPlatform === &#39;android&#39;);
let isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === &#39;ios&#39;);
let isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;

23、getExplorerInfo:获取浏览器信息

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
    }
}

24、isPCBroswer:检测是否为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)
}

以上是本次为大家整理的24个JS开发中常用的工具函数。

想了解更多JavaScript相关教程,请访问PHP中文网:https://www.php.cn/

The above is the detailed content of Summary of JS functions commonly used in front-end development (1). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)