Summary 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 == 'number' && 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() : ''; }) } //ab-cd-ef ==> abCdEf //使用记忆函数 let _camelize = cached(camelize)
17、hyphenate
:驼峰命名转横线命名:拆分字符串,使用-相连,并且转换为小写
let hyphenateRE = /\B([A-Z])/g; function hyphenate(str){ return str.replace(hyphenateRE, '-$1').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('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) )
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 'Date': case 'RegExp': case 'Error': value = new window[type](value); break; } return value }
22、识别各种浏览器及平台
//运行环境是浏览器 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;
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
