av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

JavaScript中的50+個(gè)實(shí)用工具函數(shù)小結(jié)

瀏覽:99日期:2023-09-28 11:20:21

JavaScript可以做很多出色的事情,本篇文章給大家整理50+個(gè)實(shí)用工具函數(shù),可以幫助你提高工作效率并可以幫助調(diào)試代碼

1、isStatic: 檢測(cè)數(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:檢測(cè)數(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是否是類對(duì)象。如果一個(gè)值是類對(duì)象,那么它不應(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ù)是不是正則對(duì)象

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

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

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ù)組長(zhǎng)度

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

13、isArrayLike:檢查value是否是類數(shù)組

如果一個(gè)值被認(rèn)為是類數(shù)組,那么它不是一個(gè)函數(shù),并且value.length是個(gè)整數(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ù)長(zhǎng)度;如果是Object對(duì)象,判斷是否具有屬性;如果是其他數(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)對(duì)象中

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

20、Object.assign:對(duì)象屬性復(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可以錢克隆一個(gè)對(duì)象:

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

簡(jiǎn)單的深克隆可以使用JSON.parse()和JSON.stringify(),這兩個(gè)api是解析json數(shù)據(jù)的,所以只能解析除symbol外的原始類型及數(shù)組和對(duì)象。

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

21、clone:克隆數(shù)據(jù),可深度克隆

這里列出了原始類型,時(shí)間、正則、錯(cuò)誤、數(shù)組、對(duì)象的克隆規(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)) { //是對(duì)象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、識(shí)別各種瀏覽器及平臺(tái)

//運(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 < 11type: 'IE',version: Number(t.match(/msie ([d]+)/)[1]) } : !!t.match(/trident/.+?rv:(([d.]+))/) ? { // ie 11type: '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:檢測(cè)是否為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)}

25、unique: 數(shù)組去重,返回一個(gè)新數(shù)組

function unique(arr){ if(!isArrayLink(arr)){ //不是類數(shù)組對(duì)象return arr } let result = [] let objarr = [] let obj = Object.create(null) arr.forEach(item => {if(isStatic(item)){//是除了symbol外的原始數(shù)據(jù) let key = item + ’_’ + getRawType(item); if(!obj[key]){obj[key] = trueresult.push(item) }}else{//引用類型及symbol if(!objarr.includes(item)){objarr.push(item)result.push(item) }} }) return resulte}

26、Set簡(jiǎn)單實(shí)現(xiàn)

window.Set = window.Set || (function () { function Set(arr) {this.items = arr ? unique(arr) : [];this.size = this.items.length; // Array的大小 } Set.prototype = {add: function (value) { // 添加元素,若元素已存在,則跳過(guò),返回 Set 結(jié)構(gòu)本身。 if (!this.has(value)) {this.items.push(value);this.size++; } return this;},clear: function () { //清除所有成員,沒(méi)有返回值。 this.items = [] this.size = 0},delete: function (value) { //刪除某個(gè)值,返回一個(gè)布爾值,表示刪除是否成功。 return this.items.some((v, i) => {if(v === value){ this.items.splice(i,1) return true}return false })},has: function (value) { //返回一個(gè)布爾值,表示該值是否為Set的成員。 return this.items.some(v => v === value)},values: function () { return this.items}, } return Set;}());

27、repeat:生成一個(gè)重復(fù)的字符串,有n個(gè)str組成,可修改為填充為數(shù)組等

function repeat(str, n) { let res = ’’; while(n) {if(n % 2 === 1) { res += str;}if(n > 1) { str += str;}n >>= 1; } return res};//repeat(’123’,3) ==> 123123123

28、dateFormater:格式化時(shí)間

function dateFormater(formater, t){ let date = t ? new Date(t) : new Date(),Y = date.getFullYear() + ’’,M = date.getMonth() + 1,D = date.getDate(),H = date.getHours(),m = date.getMinutes(),s = date.getSeconds(); return formater.replace(/YYYY|yyyy/g,Y).replace(/YY|yy/g,Y.substr(2,2)).replace(/MM/g,(M<10?’0’:’’) + M).replace(/DD/g,(D<10?’0’:’’) + D).replace(/HH|hh/g,(H<10?’0’:’’) + H).replace(/mm/g,(m<10?’0’:’’) + m).replace(/ss/g,(s<10?’0’:’’) + s)}// dateFormater(’YYYY-MM-DD HH:mm’, t) ==> 2019-06-26 18:30// dateFormater(’YYYYMMDDHHmm’, t) ==> 201906261830

29、dateStrForma:將指定字符串由一種時(shí)間格式轉(zhuǎn)化為另一種。From的格式應(yīng)對(duì)應(yīng)str的位置

function dateStrForma(str, from, to){ //’20190626’ ’YYYYMMDD’ ’YYYY年MM月DD日’ str += ’’ let Y = ’’ if(~(Y = from.indexOf(’YYYY’))){Y = str.substr(Y, 4)to = to.replace(/YYYY|yyyy/g,Y) }else if(~(Y = from.indexOf(’YY’))){Y = str.substr(Y, 2)to = to.replace(/YY|yy/g,Y) } let k,i [’M’,’D’,’H’,’h’,’m’,’s’].forEach(s =>{i = from.indexOf(s+s)k = ~i ? str.substr(i, 2) : ’’to = to.replace(s+s, k) }) return to}// dateStrForma(’20190626’, ’YYYYMMDD’, ’YYYY年MM月DD日’) ==> 2019年06月26日// dateStrForma(’121220190626’, ’----YYYYMMDD’, ’YYYY年MM月DD日’) ==> 2019年06月26日// dateStrForma(’2019年06月26日’, ’YYYY年MM月DD日’, ’YYYYMMDD’) ==> 20190626// 一般的也可以使用正則來(lái)實(shí)現(xiàn)//’2019年06月26日’.replace(/(d{4})年(d{2})月(d{2})日/, ’$1-$2-$3’) ==> 2019-06-26

30、getPropByPath:根據(jù)字符串路徑獲取對(duì)象屬性:‘obj[0].count’

function getPropByPath(obj, path, strict) { let tempObj = obj; path = path.replace(/[(w+)]/g, ’.$1’); //將[0]轉(zhuǎn)化為.0 path = path.replace(/^./, ’’); //去除開頭的. let keyArr = path.split(’.’); //根據(jù).切割 let i = 0; for (let len = keyArr.length; i < len - 1; ++i) {if (!tempObj && !strict) break;let key = keyArr[i];if (key in tempObj) { tempObj = tempObj[key];} else { if (strict) {//開啟嚴(yán)格模式,沒(méi)找到對(duì)應(yīng)key值,拋出錯(cuò)誤throw new Error(’please transfer a valid prop path to form item!’); } break;} } return {o: tempObj, //原始數(shù)據(jù)k: keyArr[i], //key值v: tempObj ? tempObj[keyArr[i]] : null // key值對(duì)應(yīng)的值 };};

31、GetUrlParam:獲取Url參數(shù),返回一個(gè)對(duì)象

function GetUrlParam(){ let url = document.location.toString(); let arrObj = url.split('?'); let params = Object.create(null) if (arrObj.length > 1){arrObj = arrObj[1].split('&');arrObj.forEach(item=>{ item = item.split('='); params[item[0]] = item[1]}) } return params;}// ?a=1&b=2&c=3 ==> {a: '1', b: '2', c: '3'}

32、downloadFile:base64數(shù)據(jù)導(dǎo)出文件,文件下載

function downloadFile(filename, data) { let DownloadLink = document.createElement(’a’); if (DownloadLink) {document.body.appendChild(DownloadLink);DownloadLink.style = ’display: none’;DownloadLink.download = filename;DownloadLink.href = data;if (document.createEvent) { let DownloadEvt = document.createEvent(’MouseEvents’); DownloadEvt.initEvent(’click’, true, false); DownloadLink.dispatchEvent(DownloadEvt);} else if (document.createEventObject) { DownloadLink.fireEvent(’onclick’);} else if (typeof DownloadLink.onclick == ’function’) { DownloadLink.onclick();}document.body.removeChild(DownloadLink); }}

33、toFullScreen:全屏

function toFullScreen() { let elem = document.body; elem.webkitRequestFullScreen ? elem.webkitRequestFullScreen() : elem.mozRequestFullScreen ? elem.mozRequestFullScreen() : elem.msRequestFullscreen ? elem.msRequestFullscreen() : elem.requestFullScreen ? elem.requestFullScreen() : alert('瀏覽器不支持全屏');}

34、exitFullscreen:退出全屏

function exitFullscreen() { let elem = parent.document; elem.webkitCancelFullScreen ? elem.webkitCancelFullScreen() : elem.mozCancelFullScreen ? elem.mozCancelFullScreen() : elem.cancelFullScreen ? elem.cancelFullScreen() : elem.msExitFullscreen ? elem.msExitFullscreen() : elem.exitFullscreen ? elem.exitFullscreen() : alert('切換失敗,可嘗試Esc退出');}

35、requestAnimationFrame:window動(dòng)畫

window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) {//為了使setTimteout的盡可能的接近每秒60幀的效果window.setTimeout(callback, 1000 / 60); }window.cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame || window.oCancelAnimationFrame || function (id) {//為了使setTimteout的盡可能的接近每秒60幀的效果window.clearTimeout(id); }

36、_isNaN:檢查數(shù)據(jù)是否是非數(shù)字值

function _isNaN(v){ return !(typeof v === ’string’ || typeof v === ’number’) || isNaN(v)}

37、max:求取數(shù)組中非NaN數(shù)據(jù)中的最大值

function max(arr){ arr = arr.filter(item => !_isNaN(item)) return arr.length ? Math.max.apply(null, arr) : undefined}//max([1, 2, ’11’, null, ’fdf’, []]) ==> 11

38、min:求取數(shù)組中非NaN數(shù)據(jù)中的最小值

function min(arr){ arr = arr.filter(item => !_isNaN(item)) return arr.length ? Math.min.apply(null, arr) : undefined}//min([1, 2, ’11’, null, ’fdf’, []]) ==> 1

39、random:返回一個(gè)lower-upper直接的隨機(jī)數(shù)。(lower、upper無(wú)論正負(fù)與大小,但必須是非NaN的數(shù)據(jù))

function random(lower, upper) { lower = +lower || 0 upper = +upper || 0 return Math.random() * (upper - lower) + lower;}//random(0, 0.5) ==> 0.3567039135734613//random(2, 1) ===> 1.6718418553475423//random(-2, -1) ==> -1.4474325452361945

40、Object.keys:返回一個(gè)由一個(gè)給定對(duì)象的自身可枚舉屬性組成的數(shù)組

Object.keys = Object.keys || function keys(object) { if (object === null || object === undefined) {throw new TypeError(’Cannot convert undefined or null to object’); } let result = []; if (isArrayLike(object) || isPlainObject(object)) {for (let key in object) { object.hasOwnProperty(key) && (result.push(key))} } return result;}

41、Object.values:返回一個(gè)給定對(duì)象自身的所有可枚舉屬性值的數(shù)組

Object.values = Object.values || function values(object) { if (object === null || object === undefined) {throw new TypeError(’Cannot convert undefined or null to object’); } let result = []; if (isArrayLike(object) || isPlainObject(object)) {for (let key in object) { object.hasOwnProperty(key) && (result.push(object[key]))} } return result;}

42、arr.fill:使用value值填充array,從start位置開始,到end位置結(jié)束(但不包含end位置),返回原數(shù)組

Array.prototype.fill = Array.prototype.fill || function fill(value, start, end) { let ctx = this let length = ctx.length; start = parseInt(start) if(isNaN(start)){start = 0 }else if (start < 0) {start = -start > length ? 0 : (length + start); } end = parseInt(end) if(isNaN(end) || end > length){ end = length }else if (end < 0) {end += length; } while (start < end) {ctx[start++] = value; } return ctx;}//Array(3).fill(2) ===> [2, 2, 2]

43、arr.includes:用來(lái)判斷一個(gè)數(shù)組是否包含一個(gè)指定的值,如果是返回true,否則返回false,可指定開始查詢的位置

Array.prototype.includes = Array.prototype.includes || function includes(value, start) { let ctx = this; let length = ctx.length; start = parseInt(start) if(isNaN(start)) {start = 0 } else if (start < 0) {start = -start > length ? 0 : (length + start); } let index = ctx.indexOf(value); return index >= start;}

44、返回?cái)?shù)組中通過(guò)測(cè)試(函數(shù)fn內(nèi)判斷)的第一個(gè)元素的值

Array.prototype.find = Array.prototype.find || function find(fn, ctx) { ctx = ctx || this; let result; ctx.some((value, index, arr), thisValue) => {return fn(value, index, arr) ? (result = value, true) : false }) return result}

45、arr.findIndex:返回?cái)?shù)組中通過(guò)測(cè)試(函數(shù)fn內(nèi)判斷)的第一個(gè)元素的下標(biāo)

Array.prototype.findIndex = Array.prototype.findIndex || function findIndex(fn, ctx){ ctx = ctx || this let result; ctx.some((value, index, arr), thisValue) => {return fn(value, index, arr) ? (result = index, true) : false }) return result}

46、performance.timing:利用performance.timing進(jìn)行性能分析

window.onload = function() { setTimeout(function() {let t = performance.timing;console.log(’DNS查詢耗時(shí) :’ + (t.domainLookupEnd - t.domainLookupStart).toFixed(0))console.log(’TCP鏈接耗時(shí) :’ + (t.connectEnd - t.connectStart).toFixed(0))console.log(’request請(qǐng)求耗時(shí) :’ + (t.responseEnd - t.responseStart).toFixed(0))console.log(’解析dom樹耗時(shí) :’ + (t.domComplete - t.domInteractive).toFixed(0))console.log(’白屏?xí)r間 :’ + (t.responseStart - t.navigationStart).toFixed(0))console.log(’domready時(shí)間 :’ + (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0))console.log(’onload時(shí)間 :’ + (t.loadEventEnd - t.navigationStart).toFixed(0))if (t = performance.memory) { console.log(’js內(nèi)存使用占比:’ + (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + ’%’)} })}

47、禁止某些鍵盤事件

document.addEventListener(’keydown’, function(event) { return !(112 == event.keyCode ||//禁止F1123 == event.keyCode ||//禁止F12event.ctrlKey && 82 == event.keyCode ||//禁止ctrl+Revent.ctrlKey && 18 == event.keyCode ||//禁止ctrl+Nevent.shiftKey && 121 == event.keyCode || //禁止shift+F10event.altKey && 115 == event.keyCode ||//禁止alt+F4'A' == event.srcElement.tagName && event.shiftKey//禁止shift+點(diǎn)擊a標(biāo)簽 ) || (event.returnValue = false)});

48、禁止右鍵、選擇、復(fù)制

[’contextmenu’, ’selectstart’, ’copy’].forEach(function(ev) { document.addEventListener(ev, function(event) {return event.returnValue = false; })});

49、numAdd - -計(jì)算數(shù)字相加

function numAdd(num1, num2) { let baseNum, baseNum1, baseNum2; try {baseNum1 = num1.toString().split('.')[1].length; } catch (e) {baseNum1 = 0; } try {baseNum2 = num2.toString().split('.')[1].length; } catch (e) {baseNum2 = 0; } baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); return (num1 * baseNum + num2 * baseNum) / baseNum;};

50、numSub - - 計(jì)算數(shù)字相減

function numSub(num1, num2) { let baseNum, baseNum1, baseNum2; let precision;// 精度 try {baseNum1 = num1.toString().split('.')[1].length; } catch (e) {baseNum1 = 0; } try {baseNum2 = num2.toString().split('.')[1].length; } catch (e) {baseNum2 = 0; } baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2; return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);};

51、numMulti - - 計(jì)算數(shù)字相乘

function numMulti(num1, num2) { let baseNum = 0; try {baseNum += num1.toString().split('.')[1].length; } catch (e) { } try {baseNum += num2.toString().split('.')[1].length; } catch (e) { } return Number(num1.toString().replace('.', '')) * Number(num2.toString().replace('.', '')) / Math.pow(10, baseNum);};

52、numDiv - - 計(jì)算數(shù)字相除

function numDiv(num1, num2) { let baseNum1 = 0, baseNum2 = 0; let baseNum3, baseNum4; try {baseNum1 = num1.toString().split('.')[1].length; } catch (e) {baseNum1 = 0; } try {baseNum2 = num2.toString().split('.')[1].length; } catch (e) {baseNum2 = 0; } with (Math) {baseNum3 = Number(num1.toString().replace('.', ''));baseNum4 = Number(num2.toString().replace('.', ''));return (baseNum3 / baseNum4) * pow(10, baseNum2 - baseNum1); }};

到此這篇關(guān)于JavaScript中的50+個(gè)實(shí)用工具函數(shù)小結(jié)的文章就介紹到這了,更多相關(guān)JavaScript 實(shí)用工具函數(shù)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 国产日韩欧美精品 | 特级丰满少妇一级aaaa爱毛片 | 欧美一级在线播放 | 亚洲国产中文字幕 | 日本黄色录像 | av观看网站 | 欧美国产激情 | 国产精品99久久久久久久久久久久 | 亚洲第一在线 | 欧美成人一区二区 | 亚洲三级免费 | 天天做天天爱 | 四虎精品在线 | 午夜一级片 | 欧美一级黄 | 中文字幕av久久爽av | 天天操天天碰 | 色婷婷色 | 国产一区二区三区视频 | 欧美成人极品 | 特级西西444www大精品视频 | 黄色一级免费视频 | 中文亚洲字幕 | 激情五月婷婷 | 国产精品人人做人人爽人人添 | 午夜精品久久久久久久99黑人 | 狠狠干 | 香蕉伊人网| 成人精品三级av在线看 | 亚洲经典一区二区 | 午夜一级片 | 美国式禁忌14在线 | 日本不卡视频 | 91视频精选 | 福利视频网站 | www.中文字幕.com | 一区二区三区四区精品 | 97视频免费 | 日韩亚洲一区二区 | 午夜成人在线视频 | 一级黄色免费视频 |