你要的幾個JS實用工具函數(shù)(持續(xù)更新)
今天,我們來總結(jié)下我們平常使用的工具函數(shù),希望對大家有用。
1、封裝fetch
源碼:
/**
* 封裝fetch函數(shù),用Promise做回調(diào)
* @type {{get: (function(*=)), post: (function(*=, *=))}}
*/
const fetchUtil = {
get: (url) => {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}).then((response) => response.json()).then(response => {
resolve(response);
}).catch(err => {
reject(new Error(err));
});
});
},
post: (url, params) => {
return new Promise((resolve, reject) => {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params
}).then((response) => response.json()).then(response => {
resolve(response);
}).catch(err => {
reject(new Error(err));
});
});
}
};
export default fetchUtil;
使用:
import Fetch from "../util/FetchUtil.js";
// post請求
post(){
let params = "";
params += "phone=" + "xxxxxx" + "&password="+"123456";
Fetch.post("https://carvedu.com/api/user/sms", this.params)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
// get請求
get() {
Fetch.get("https://carvedu.com/api/courses")
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
2、判斷瀏覽器環(huán)境
源碼:
function getSystem(){
const mac = /mac/i,
linux = /linux/i,
win = /win/i;
const platform = navigator.platform.toLowerCase();
if(mac.test(platform)){
return 'MAC';
} else if(win.test(platform)){
return 'WIN';
} else if(linux.test(platform)){
return 'Linux';
}
return undefined;
}
const browser = {
versions:function(){
let ret = 'xxSys';
const u = navigator.userAgent;
const isMobile = !!u.match(/AppleWebKit.*Mobile.*/),
ios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
if(isMobile){
if(ios) return 'IOS';
if(android) return 'Android';
} else {
ret = getSystem() || ret;
}
return ret;
}(),
};
export default browser;
使用:
import browser from "../util/browers.js"
console.log(browser.versions);
3、計算時間差
源碼:
let startTime = new Date().getTime();
export const start = (v) =>{
if(v==='reset'){
return startTime = new Date().getTime();
} else{
return startTime;
}
}
使用:
import {start} from "../util/Time.js"
click(){
let userTime = new Date().getTime()-start();
start('reset');
}
4、封裝正則庫
源碼:
export default {
// 正則
regExp:()=>{
return {
mPattern :/^1[345789]\d{9}$/, //手機號驗證規(guī)則
cP : /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, // 身份證驗證規(guī)則
regCode : /^\d{4}$/ //驗證碼規(guī)則
/*......*/
}
}
}
使用:
import regExp from '../util/regExp.js'
reg(){
var value ="" // 手機號碼舉例
console.log(regExp.regExp().mPattern.test(value));
},
5、判斷瀏覽器是否支持攝像頭
源碼:
export default {
// 判斷有無攝像頭
videoCheck:()=>{
var deviceList = [];
navigator.mediaDevices
.enumerateDevices()
.then(devices => {
devices.forEach(device => {
deviceList.push(device.kind);
});
if (deviceList.indexOf("videoinput") == "-1") {
console.info("沒有攝像頭");
return false;
} else {
console.info("有攝像頭");
}
})
.catch(function(err) {
alert(err.name + ": " + err.message);
});
},
}
使用:
import videoCheck from '../util/videoCheck.js'
videoCheck.videoCheck();
6、圖片是否加載完成
源碼:
export default {
// 圖片加載
imgLoad:(src)=>{
let bgImg = new Image();
bgImg.src = src; // 獲取背景圖片的url
bgImg.onerror = () => {
console.log("img onerror");
};
bgImg.onload = () => {
console.log("加載完成");
return false
};
}
}
使用:
import imgLoad from '../util/imgLoad'
imgLoad.imgLoad('這里寫圖片的地址');
7、解析html字符串
源碼:
export default {
getHtmlobj:(htmlobj)=>{
var el = document.createElement('div');
el.innerHTML = htmlobj;
var tags = el.getElementsByTagName('img');
var text = tags[0].getAttribute("src");
return text;
}
}
使用:
import getHtmlobj from '../util/getHtmlobj';
const htmlobj = '<div><p>標簽</p><img src="ggg"/></div>';
getHtmlobj(htmlobj);
8、定義數(shù)組內(nèi)部對象形式
export const objArrtransArr = (olddata, oldval, oldname)=>{
const newArr = [];
olddata.forEach(item => {
// 定義數(shù)組內(nèi)部對象形式
let obj = {};
obj.value = item[oldval];
obj.name = item[oldname];
// 將對象數(shù)據(jù)推到數(shù)組中
newArr.push(obj);
});
return newArr;
}
作者:Vam的金豆之路
主要領(lǐng)域:前端開發(fā)
我的微信:maomin9761
微信公眾號:前端歷劫之路