溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JS開發(fā)中常用的工具函數(shù)有哪些

發(fā)布時間:2021-09-28 13:43:21 來源:億速云 閱讀:141 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“JS開發(fā)中常用的工具函數(shù)有哪些”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“JS開發(fā)中常用的工具函數(shù)有哪些”這篇文章吧。

1、isStatic: 檢測數(shù)據(jù)是不是除了symbol外的原始數(shù)據(jù)。

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

2、isPrimitive:檢測數(shù)據(jù)是不是原始數(shù)據(jù)

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

3、isObject:判斷數(shù)據(jù)是不是引用類型的數(shù)據(jù)(例如: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是否是類對象。如果一個值是類對象,那么它不應(yīng)該是null,而且typeof后的結(jié)果是“object”。

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

5、getRawType:獲取數(shù)據(jù)類型,返回結(jié)果為Number、String、Object、Array等

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

6、isPlainObject:判斷數(shù)據(jù)是不是Object類型的數(shù)據(jù)

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

7、isArray:判斷數(shù)據(jù)是不是數(shù)組類型的數(shù)據(jù)(Array.isArray的兼容寫法)

function isArray(arr) {return Object.prototype.toString.call(arr) === '[object Array]'}// 將isArray掛載到Array上Array.isArray = Array.isArray || isArray;

8、isRegExp:判斷數(shù)據(jù)是不是正則對象

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

9、isDate:判斷數(shù)據(jù)是不是時間對象

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

10、isNative:判斷value是不是瀏覽器內(nèi)置函數(shù)內(nèi)置函數(shù)toString后的主體代碼塊為[native code] ,而非內(nèi)置函數(shù)則為相關(guān)代碼,所以非內(nèi)置函數(shù)可以進(jìn)行拷貝(toString后掐頭去尾再由Function轉(zhuǎn))

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

11、isFunction:檢查value是不是函數(shù)

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

12、isLength:檢查value是否為有效的類數(shù)組長度

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

13、isArrayLike:檢查value是否是類數(shù)組如果一個值被認(rèn)為是類數(shù)組,那么它不是一個函數(shù),并且value.length是個整數(shù),大于等于0,小于或等于Number.MAX_SAFE_INTEGER。這里字符串也被當(dāng)作類數(shù)組。

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

14、isEmpty:檢查value是否為空如果是null,直接返回true;如果是類數(shù)組,判斷數(shù)據(jù)長度;如果是Object對象,判斷是否具有屬性;如果是其他數(shù)據(jù),直接返回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:記憶函數(shù):緩存函數(shù)的運(yùn)算結(jié)果

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

16、camelize:橫線轉(zhuǎn)駝峰命名

let camelizeRE = /-(\w)/g;function camelize(str) {return str.replace(camelizeRE, function(_, c) {return c ? c.toUpperCase() : '';})}//ab-cd-ef ==> abCdEf//使用記憶函數(shù)let _camelize = cached(camelize)

17、hyphenate:駝峰命名轉(zhuǎn)橫線命名:拆分字符串,使用-相連,并且轉(zhuǎn)換為小寫

let hyphenateRE = /\B([A-Z])/g;function hyphenate(str){    return str.replace(hyphenateRE, '-$1').toLowerCase()}//abCd ==> ab-cd//使用記憶函數(shù)let _hyphenate = cached(hyphenate);

18、capitalize:字符串首位大寫

function capitalize(str) {return str.charAt(0).toUpperCase() + str.slice(1)}// abc ==> Abc//使用記憶函數(shù)let _capitalize = cached(capitalize)

19、extend:將屬性混合到目標(biāo)對象中

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

20、Object.assign:對象屬性復(fù)制,淺拷貝

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數(shù)據(jù)的,所以只能解析除symbol外的原始類型及數(shù)組和對象。

let clone = JSON.parse( JSON.stringify(target) )

21、clone:克隆數(shù)據(jù),可深度克隆這里列出了原始類型,時間、正則、錯誤、數(shù)組、對象的克隆規(guī)則,其他的可自行補(bǔ)充

function clone(value, deep) {if (isPrimitive(value)) {return value}if (isArrayLike(value)) {  //是類數(shù)組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、識別各種瀏覽器及平臺

//運(yùn)行環(huán)境是瀏覽器let inBrowser = typeof window !== 'undefined';//運(yùn)行環(huán)境是微信let inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;let weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();//瀏覽器 UA 判斷l(xiāng)et 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)}

以上是“JS開發(fā)中常用的工具函數(shù)有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

js
AI