JS 開發經常使用工具函數

 

一、isStatic:檢測數據是否是除了symbol外的原始數據android

 

function isStatic(value) {ios

return(git

typeofvalue === 'string' ||github

typeofvalue === 'number' ||web

typeofvalue === 'boolean' ||chrome

typeofvalue === 'undefined' ||json

value === nullsegmentfault

    )windows

}api

 

二、isPrimitive:檢測數據是否是原始數據

 

function isPrimitive(value) {

return isStatic(value) || typeofvalue === 'symbol'

}

 

三、isObject:判斷數據是否是引用類型的數據 (例如: arrays, functions, objects, regexes, new Number(0),以及 new String(''))

 

function isObject(value) {

let type = typeofvalue;

returnvalue != null && (type == 'object' || type == 'function');

}

 

四、isObjectLike:檢查 value 是不是 類對象。 若是一個值是類對象,那麼它不該該是 null,並且 typeof 後的結果是 "object"

 

function isObjectLike(value) {

returnvalue != null && typeofvalue == 'object';

}

 

五、getRawType:獲取數據類型,返回結果爲 Number、String、Object、Array等

 

functiongetRawType(value) {

returnObject.prototype.toString.call(value).slice(8, -1)

}

//getoRawType([]) ==> Array

 

六、isPlainObject:判斷數據是否是Object類型的數據

 

functionisPlainObject(obj) {

returnObject.prototype.toString.call(obj) === '[object Object]'

}

 

七、isArray:判斷數據是否是數組類型的數據

 

functionisArray(arr) {

returnObject.prototype.toString.call(arr) === '[object Array]'

}

 

將isArray掛載到Array上

 

Array.isArray = Array.isArray || isArray;

 

八、isRegExp:判斷數據是否是正則對象

 

functionisRegExp(value) {

returnObject.prototype.toString.call(value) === '[object RegExp]'

}

 

九、isDate:判斷數據是否是時間對象

 

functionisDate(value) {

returnObject.prototype.toString.call(value) === '[object Date]'

}

 

十、isNative:判斷 value 是否是瀏覽器內置函數

 

內置函數toString後的主體代碼塊爲 [native code] ,而非內置函數則爲相關代碼,因此非內置函數能夠進行拷貝(toString後掐頭去尾再由Function轉)

 

function isNative(value) {

returntypeofvalue === 'function' && /native code/.test(value.toString())

}

 

十一、isFunction:檢查 value 是否是函數

 

functionisFunction(value) {

returnObject.prototype.toString.call(value) === '[object Function]'

}

 

十二、isLength:檢查 value 是否爲有效的類數組長度

 

function isLength(value) {

returntypeofvalue == 'number' && value > -1 && value % 1 == 0 && value <= Number.MAX_SAFE_INTEGER;

}

 

1三、isArrayLike:檢查 value 是不是類數組

 

若是一個值被認爲是類數組,那麼它不是一個函數,而且value.length是個整數,大於等於 0,小於或等於 Number.MAX_SAFE_INTEGER。這裏字符串也將被看成類數組。

 

function isArrayLike(value) {

returnvalue != null && isLength(value.length) && !isFunction(value);

}

 

1四、isEmpty:檢查 value 是否爲空

 

若是是null,直接返回true;若是是類數組,判斷數據長度;若是是Object對象,判斷是否具備屬性;若是是其餘數據,直接返回false(也可改成返回true)

 

function isEmpty(value) {

if (value == null) {

returntrue;

    }

if (isArrayLike(value)) {

return !value.length;

    }elseif(isPlainObject(value)){

for (let key invalue) {

if (hasOwnProperty.call(value, key)) {

returnfalse;

            }

        }

returntrue;

    }

returnfalse;

}

 

1五、cached:記憶函數:緩存函數的運算結果

 

functioncached(fn) {

let cache = Object.create(null);

returnfunctioncachedFn(str) {

let hit = cache[str];

return hit || (cache[str] = fn(str))

    }

}

 

1六、camelize:橫線轉駝峯命名

 

let camelizeRE = /-(w)/g;

functioncamelize(str) {

return str.replace(camelizeRE, function(_, c) {

return c ? c.toUpperCase() : '';

    })

}

//ab-cd-ef ==> abCdEf

//使用記憶函數

let _camelize = cached(camelize)

 

1七、hyphenate:駝峯命名轉橫線命名:拆分字符串,使用 - 相連,而且轉換爲小寫

 

let hyphenateRE = /B([A-Z])/g;

functionhyphenate(str){

return str.replace(hyphenateRE, '-$1').toLowerCase()

}

//abCd ==> ab-cd

//使用記憶函數

let _hyphenate = cached(hyphenate);

 

1八、capitalize:字符串首位大寫

 

functioncapitalize(str){

return str.charAt(0).toUpperCase() + str.slice(1)

}

// abc ==> Abc

//使用記憶函數

let _capitalize = cached(capitalize)

 

1九、extend:將屬性混合到目標對象中

 

functionextend(to, _from) {

for(let key in _from) {

        to[key] = _from[key];

    }

return to

}

 

20、Object.assign:對象屬性複製,淺拷貝

 

Object.assign = Object.assign || function(){

if(arguments.length == 0) thrownewTypeError('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能夠淺克隆一個對象:

 

letclone = Object.assign({}, target)

 

簡單的深克隆可使用JSON.parse()和JSON.stringify(),這兩個api是解析json數據的,因此只能解析除symbol外的原始類型及數組和對象

 

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

 

2一、clone:克隆數據,可深度克隆

 

這裏列出了原始類型,時間、正則、錯誤、數組、對象的克隆規則,其餘的可自行補充

 

function clone(value, deep){

if(isPrimitive(value)){

returnvalue

    }

 

if (isArrayLike(value)) { //是類數組

value = Array.prototype.slice.call(value)

returnvalue.map(item => deep ? clone(item, deep) : item)

       }elseif(isPlainObject(value)){ //是對象

let target = {}, key;

for (key invalue) {

value.hasOwnProperty(key) && ( target[key] = deep ? clone(value[key], deep) : value[key] )

        }

    }

 

let type = getRawType(value)

 

switch(type){

case'Date':

case'RegExp': 

case'Error': value = new window[type](value); break;

    }

returnvalue

}

 

2二、識別各類瀏覽器及平臺

 

//運行環境是瀏覽器

let inBrowser = typeofwindow !== '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;

 

2三、getExplorerInfo:獲取瀏覽器信息

 

functiongetExplorerInfo() {

let t = navigator.userAgent.toLowerCase();

return0 <= 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

    }

}

 

2四、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)

}

 

2五、unique:數組去重,返回一個新數組

 

functionunique(arr){

if(!isArrayLink(arr)){ //不是類數組對象

return arr

    }

let result = []

let objarr = []

let obj = Object.create(null)

 

    arr.forEach(item => {

if(isStatic(item)){//是除了symbol外的原始數據

let key = item + '_' + getRawType(item);

if(!obj[key]){

                obj[key] = true

                result.push(item)

            }

        }else{//引用類型及symbol

if(!objarr.includes(item)){

                objarr.push(item)

                result.push(item)

            }

        }

    })

 

return resulte

}

 

2六、Set簡單實現

 

window.Set = window.Set || (function () {

functionSet(arr) {

this.items = arr ? unique(arr) : [];

this.size = this.items.length; // Array的大小

    }

Set.prototype = {

add: function (value) {

// 添加元素,若元素已存在,則跳過,返回 Set 結構自己。

if (!this.has(value)) {

this.items.push(value);

this.size++;

            }

returnthis;

        },

clear: function () {

//清除全部成員,沒有返回值。

this.items = []

this.size = 0

        },

delete: function (value) {

//刪除某個值,返回一個布爾值,表示刪除是否成功。

returnthis.items.some((v, i) => {

if(v === value){

this.items.splice(i,1)

returntrue

                }

returnfalse

            })

        },

has: function (value) {

//返回一個布爾值,表示該值是否爲Set的成員。

returnthis.items.some(v => v === value)

        },

values: function () {

returnthis.items

        },

    }

 

returnSet;

}());

 

2七、repeat:生成一個重複的字符串,有n個str組成,可修改成填充爲數組等

 

functionrepeat(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

 

2八、dateFormater:格式化時間

 

functiondateFormater(formater, t){

let date = t ? newDate(t) : newDate(),

        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

 

2九、dateStrForma:將指定字符串由一種時間格式轉化爲另外一種

from的格式應對應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)

    }elseif(~(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

 

// 通常的也可使用正則來實現

//'2019年06月26日'.replace(/(d{4})年(d{2})月(d{2})日/, '$1-$2-$3') ==>2019-06-26

 

30、getPropByPath:根據字符串路徑獲取對象屬性 : 'obj[0].count'

 

functiongetPropByPath(obj, path, strict) {

let tempObj = obj;

      path = path.replace(/[(w+)]/g, '.$1'); //將[0]轉化爲.0

      path = path.replace(/^./, ''); //去除開頭的.

 

let keyArr = path.split('.'); //根據.切割

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) {//開啓嚴格模式,沒找到對應key值,拋出錯誤

thrownewError('please transfer a valid prop path to form item!');

            }

break;

        }

      }

return {

o: tempObj, //原始數據

        k: keyArr[i], //key值

        v: tempObj ? tempObj[keyArr[i]] : null// key值對應的值

      };

};

 

3一、GetUrlParam:獲取Url參數,返回一個對象

 

functionGetUrlParam(){

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

 

3二、downloadFile:base64數據導出文件,文件下載

 

functiondownloadFile(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);

        }

elseif ( document.createEventObject )

            DownloadLink.fireEvent('onclick');

elseif (typeof DownloadLink.onclick == 'function' )

            DownloadLink.onclick();

 

document.body.removeChild(DownloadLink);

    }

}

 

3三、toFullScreen:全屏

 

functiontoFullScreen(){

let elem = document.body;

    elem.webkitRequestFullScreen 

    ? elem.webkitRequestFullScreen()

    : elem.mozRequestFullScreen

    ? elem.mozRequestFullScreen()

    : elem.msRequestFullscreen

    ? elem.msRequestFullscreen()

    : elem.requestFullScreen

    ? elem.requestFullScreen()

    : alert("瀏覽器不支持全屏");

}

 

3四、exitFullscreen:退出全屏

 

functionexitFullscreen(){

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退出");

}

 

3五、requestAnimationFrame:window動畫

 

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

    }

 

3六、_isNaN:檢查數據是不是非數字值

 

原生的isNaN會把參數轉換成數字(valueof),而null、true、false以及長度小於等於1的數組(元素爲非NaN數據)會被轉換成數字,這不是我想要的。Symbol類型的數據不具備valueof接口,因此isNaN會拋出錯誤,這裏放在後面,可避免錯誤

 

function_isNaN(v){

return !(typeof v === 'string' || typeof v === 'number') || isNaN(v)

}

 

3七、max:求取數組中非NaN數據中的最大值

 

functionmax(arr){

    arr = arr.filter(item => !_isNaN(item))

return arr.length ? Math.max.apply(null, arr) : undefined

}

//max([1, 2, '11', null, 'fdf', []]) ==> 11

 

3八、min:求取數組中非NaN數據中的最小值

 

functionmin(arr){

    arr = arr.filter(item => !_isNaN(item))

return arr.length ? Math.min.apply(null, arr) : undefined

}

//min([1, 2, '11', null, 'fdf', []]) ==> 1

 

3九、random:返回一個lower - upper之間的隨機數

 

lower、upper不管正負與大小,但必須是非NaN的數據

 

functionrandom(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:返回一個由一個給定對象的自身可枚舉屬性組成的數組

 

Object.keys = Object.keys || function keys(object) {

if(object === null || object === undefined){

thrownew TypeError('Cannot convert undefined or null to object');

    }

let result = []

if(isArrayLike(object) || isPlainObject(object)){

for (let key inobject) {

object.hasOwnProperty(key) && ( result.push(key) )

        }

    }

return result

}

 

4一、Object.values:返回一個給定對象自身的全部可枚舉屬性值的數組

 

Object.values = Object.values || function values(object) {

if(object === null || object === undefined){

thrownew TypeError('Cannot convert undefined or null to object');

    }

let result = []

if(isArrayLike(object) || isPlainObject(object)){

for (let key inobject) {

object.hasOwnProperty(key) && ( result.push(object[key]) )

        }

    }

return result

}

 

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

 

Array.prototype.fill = Array.prototype.fill || functionfill(value, start, end) {

let ctx = this

let length = ctx.length;

 

    start = parseInt(start)

if(isNaN(start)){

        start = 0

    }elseif (start < 0) {

        start = -start > length ? 0 : (length + start);

      }

 

      end = parseInt(end)

if(isNaN(end) || end > length){

          end = length

      }elseif (end < 0) {

        end += length;

    }

 

while (start < end) {

        ctx[start++] = value;

    }

return ctx;

}

//Array(3).fill(2) ===> [2, 2, 2]

 

4三、arr.includes:用來判斷一個數組是否包含一個指定的值,若是是返回 true,不然false,可指定開始查詢的位置

 

Array.prototype.includes = Array.prototype.includes || functionincludes(value, start){

let ctx = this

let length = ctx.length;

 

    start = parseInt(start)

if(isNaN(start)){

        start = 0

    }elseif (start < 0) {

        start = -start > length ? 0 : (length + start);

      }

 

let index = ctx.indexOf(value)

 

return index >= start;

}

 

4四、arr.find:返回數組中經過測試(函數fn內判斷)的第一個元素的值

 

Array.prototype.find = Array.prototype.find || functionfind(fn, ctx){

    fn = fn.bind(ctx)

 

let result;

this.some((value, index, arr), thisValue) => {

return fn(value, index, arr) ? (result = value, true) : false

    })

 

return result

}

 

4五、arr.findIndex :返回數組中經過測試(函數fn內判斷)的第一個元素的下標

 

Array.prototype.findIndex = Array.prototype.findIndex || functionfindIndex(fn, ctx){

    fn = fn.bind(ctx)

 

let result;

this.some((value, index, arr), thisValue) => {

return fn(value, index, arr) ? (result = index, true) : false

    })

 

return result

}

 

4六、performance.timing:利用performance.timing進行性能分析

 

window.onload = function(){

    setTimeout(function(){

let t = performance.timing

console.log('DNS查詢耗時 :' + (t.domainLookupEnd - t.domainLookupStart).toFixed(0))

console.log('TCP連接耗時 :' + (t.connectEnd - t.connectStart).toFixed(0))

console.log('request請求耗時 :' + (t.responseEnd - t.responseStart).toFixed(0))

console.log('解析dom樹耗時 :' + (t.domComplete - t.domInteractive).toFixed(0))

console.log('白屏時間 :' + (t.responseStart - t.navigationStart).toFixed(0))

console.log('domready時間 :' + (t.domContentLoadedEventEnd - t.navigationStart).toFixed(0))

console.log('onload時間 :' + (t.loadEventEnd - t.navigationStart).toFixed(0))

 

if(t = performance.memory){

console.log('js內存使用佔比 :' + (t.usedJSHeapSize / t.totalJSHeapSize * 100).toFixed(2) + '%')

        }

    })

}

 

4七、禁止某些鍵盤事件:

 

document.addEventListener('keydown', function(event){

return !(

112 == event.keyCode || //F1

123 == event.keyCode || //F12

event.ctrlKey && 82 == event.keyCode || //ctrl + R

event.ctrlKey && 78 == event.keyCode || //ctrl + N

event.shiftKey && 121 == event.keyCode || //shift + F10

event.altKey && 115 == event.keyCode || //alt + F4

"A" == event.srcElement.tagName && event.shiftKey //shift + 點擊a標籤

    ) || (event.returnValue = false)

});

 

4八、禁止右鍵、選擇、複製

 

['contextmenu', 'selectstart', 'copy'].forEach(function(ev){

document.addEventListener(ev, function(event){

return event.returnValue = false

    })

});

github地址:https://github.com/hfhan/tools

連接:https://segmentfault.com/a/1190000019601333

相關文章
相關標籤/搜索