[关闭]
@Bios 2018-12-10T08:44:10.000000Z 字数 11356 阅读 791

JavaScript函数库

js


  1. Array.prototype.distinct = function(){
  2. var arr = this;
  3. var len = this.length;
  4. var result = [];
  5. if (Set) { // Es6 语法
  6. return Array.from(new Set(arr));
  7. } else { // 循环比较,依次找出数组中独立的项
  8. for (var i = 0; i < len; i++) {
  9. for (var j = i + 1; j < len; j++){
  10. if (arr[i] === arr[j]) { // 1 和 '1'
  11. j = ++i;
  12. }
  13. }
  14. result.push(arr[i]);
  15. }
  16. return result;
  17. }
  18. }
  1. isIos () {
  2. var u = navigator.userAgent;
  3. if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {//安卓手机
  4. // return "Android";
  5. return false
  6. } else if (u.indexOf('iPhone') > -1) {//苹果手机
  7. // return "iPhone";
  8. return true
  9. } else if (u.indexOf('iPad') > -1) {//iPad
  10. // return "iPad";
  11. return false
  12. } else if (u.indexOf('Windows Phone') > -1) {//winphone手机
  13. // return "Windows Phone";
  14. return false
  15. }else{
  16. return false
  17. }
  18. }
  1. isPC () { //是否为PC端
  2. var userAgentInfo = navigator.userAgent;
  3. var Agents = ["Android", "iPhone",
  4. "SymbianOS", "Windows Phone",
  5. "iPad", "iPod"];
  6. var flag = true;
  7. for (var v = 0; v < Agents.length; v++) {
  8. if (userAgentInfo.indexOf(Agents[v]) > 0) {
  9. flag = false;
  10. break;
  11. }
  12. }
  13. return flag;
  14. }
  1. browserType(){
  2. var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  3. var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
  4. var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
  5. var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
  6. var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
  7. var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
  8. var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器
  9. var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
  10. if (isIE) {
  11. var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
  12. reIE.test(userAgent);
  13. var fIEVersion = parseFloat(RegExp["$1"]);
  14. if(fIEVersion == 7) return "IE7"
  15. else if(fIEVersion == 8) return "IE8";
  16. else if(fIEVersion == 9) return "IE9";
  17. else if(fIEVersion == 10) return "IE10";
  18. else return "IE7以下"//IE版本过低
  19. }
  20. if (isIE11) return 'IE11';
  21. if (isEdge) return "Edge";
  22. if (isFF) return "FF";
  23. if (isOpera) return "Opera";
  24. if (isSafari) return "Safari";
  25. if (isChrome) return "Chrome";
  26. }
  1. checkStr (str, type) {
  2. switch (type) {
  3. case 'phone': //手机号码
  4. return /^1[3|4|5|6|7|8][0-9]{9}$/.test(str);
  5. case 'tel': //座机
  6. return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
  7. case 'card': //身份证
  8. return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
  9. case 'pwd': //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线
  10. return /^[a-zA-Z]\w{5,17}$/.test(str)
  11. case 'postal': //邮政编码
  12. return /[1-9]\d{5}(?!\d)/.test(str);
  13. case 'QQ': //QQ号
  14. return /^[1-9][0-9]{4,9}$/.test(str);
  15. case 'email': //邮箱
  16. return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
  17. case 'money': //金额(小数点2位)
  18. return /^\d*(?:\.\d{0,2})?$/.test(str);
  19. case 'URL': //网址
  20. return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
  21. case 'IP': //IP
  22. return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
  23. case 'date': //日期时间
  24. return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
  25. case 'number': //数字
  26. return /^[0-9]$/.test(str);
  27. case 'english': //英文
  28. return /^[a-zA-Z]+$/.test(str);
  29. case 'chinese': //中文
  30. return /^[\u4E00-\u9FA5]+$/.test(str);
  31. case 'lower': //小写
  32. return /^[a-z]+$/.test(str);
  33. case 'upper': //大写
  34. return /^[A-Z]+$/.test(str);
  35. case 'HTML': //HTML标记
  36. return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
  37. default:
  38. return true;
  39. }

localStorage

  1. /**
  2. * 本地存储
  3. * @param {[type]} name [description]
  4. * @param {[type]} data [description]
  5. */
  6. setStorage(name, data){
  7. let dataType = typeof data;
  8. // json对象
  9. if(dataType === 'object'){
  10. window.localStorage.setItem(name, JSON.stringify(data));
  11. }
  12. // 基础类型
  13. else if(['number','string','boolean'].indexOf(dataType) >= 0){
  14. window.localStorage.setItem(name, data);
  15. }
  16. // 其他不支持的类型
  17. else{
  18. alert('该类型不能用于本地存储');
  19. }
  20. }
  21. /**
  22. * 取出本地存储
  23. * @param {[type]} name [description]
  24. * @return {[type]} [description]
  25. */
  26. getStorage(name){
  27. let data = window.localStorage.getItem(name);
  28. if(data){
  29. return JSON.parse(data);
  30. }
  31. else{
  32. return '';
  33. }
  34. }
  35. /**
  36. * 删除本地存储
  37. * @param {[type]} name [description]
  38. * @return {[type]} [description]
  39. */
  40. removeStorage(name){
  41. window.localStorage.removeItem(name);
  42. }

http请求封装(超时终止)

  1. const delay = timeout => {
  2. return new Promise((resolve, reject) => {
  3. setTimeout(() => reject('请求超时!'), timeout * 1000)
  4. })
  5. }
  6. /**
  7. * http请求
  8. * @param {[type]} options.url [请求地址]
  9. * @param {String} options.method [请求方法]
  10. * @param {Object} options.params [请求参数]
  11. * @param {[type]} timeout} [超时时间]
  12. * @return {[type]} [Promise]
  13. */
  14. const httpReq = ({url,method = 'get',params = {}, timeout}) => {
  15. const paramArr = [];
  16. /**
  17. * var obj = {'a':'123','b':'345'};
  18. * console.log(Object.keys(obj)); //['a','b']
  19. */
  20. if (Object.keys(params).length !== 0) {
  21. for (const key in params) {
  22. paramArr.push(`${key}=${params[key]}`);
  23. }
  24. }
  25. const urlStr = `${url}?${paramArr.join('&')}`; // get请求url拼接
  26. const body = paramArr.join('&'); // post请求body传参
  27. let options = {};
  28. options = {
  29. method: 'POST',
  30. headers: {
  31.     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  32.    },
  33. body: body
  34. }
  35. if (method.toLowerCase() === 'get'){
  36. if (timeout === undefined) {
  37. return fetch(urlStr)
  38. } else {
  39. // Promise.race当数组中有一个promise返回则返回,其余的不再执行。如果超时了就不执行了
  40. return Promise.race([fetch(urlStr), delay(timeout)])
  41. }
  42. } else if (method.toLowerCase() === 'post') {
  43. if (timeout === undefined) {
  44. return fetch(url,options)
  45. } else {
  46. return Promise.race([fetch(url,options), delay(timeout)])
  47. }
  48. } else {
  49. return new Promise((resolve,reject) => {
  50. resolve('不支持该请求!');
  51. })
  52. }
  53. }
  54. export { httpReq }

get请求参数的设置:

使用:

axios

  1. // import axios from "axios";
  2. //这样写打包的时候就不用切换开发环境和线上环境地址了
  3. // console.log(process.env.NODE_ENV) // 看config下面dev.env.js里面的NODE_ENV
  4. // const baseURL = process.env.NODE_ENV == 'development'?'https://cnodejs.org/api/v1':'线上环境地址'
  5. // export default axios.create({
  6. // //urlbase
  7. // baseURL,
  8. // //查询axios配置,可以设置全局请求头,全局拦截器(请求/响应)
  9. // });
  10. // ---------------------------------------------------------------------
  11. // https://www.cnblogs.com/libin-1/p/6607945.html
  12. import axios from 'axios';
  13. import { Message } from 'element-ui';
  14. // import Vue from 'vue'
  15. // import router from 'vue-router'
  16. // Vue.use(router)
  17. axios.defaults.timeout = 5000;
  18. axios.defaults.baseURL ='https://cnodejs.org/api/v1';
  19. //http request 拦截器
  20. axios.interceptors.request.use(
  21. config => {
  22. //在发送请求之前做某事
  23. // 有的请求需要token验证,token一般存cookie,他就拿到 统一给所有请求加上token字段
  24. // const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
  25. // console.log("请求之前")
  26. // console.log(config)
  27. config.headers = {
  28. 'Content-Type':'application/x-www-form-urlencoded'
  29. }
  30. // if(token){
  31. // config.params = {'token':token}
  32. // }
  33. return config;
  34. },
  35. err => {
  36. return Promise.reject(err);
  37. }
  38. );
  39. //http response 拦截器
  40. axios.interceptors.response.use(
  41. response => {
  42. //对响应数据做些事
  43. // var responses = JSON.stringify(response);
  44. // if(response.status == 200){
  45. // // alert(123)
  46. // }else if(response.status == 404){
  47. // alert("找不到")
  48. // }
  49. // console.log(response)
  50. //登录机制--在某个页面,有时候用户没有登录 导致 请求里面没有携带登录所需要的验证机制 所以会返回一些特殊的状态码 约定好的,拦截到这样的状态码 可以给跳转操作,a跳槽到c 并且传参数告诉c 是我a传过去的,这样你登录完了 得知 是a跳转过来的
  51. // if(response.data.errCode == 2){
  52. // router.push({
  53. // path:"/HelloWorld",
  54. // querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
  55. // })
  56. // }
  57. return response;
  58. },
  59. err => {
  60. //请求错误时做些事
  61. if (err && err.response) {
  62. switch (err.response.status) {
  63. case 400:
  64. err.message = '请求出错'
  65. break
  66. case 401:
  67. Message.warning({
  68. message: '授权失败,请重新登录'
  69. })
  70. store.commit('LOGIN_OUT')
  71. setTimeout(() => {
  72. window.location.reload()
  73. }, 1000)
  74. return
  75. case 403:
  76. err.message = '拒绝访问'
  77. break
  78. case 404:
  79. err.message = '请求错误,未找到该资源'
  80. break
  81. case 500:
  82. err.message = '服务器端出错'
  83. break
  84. }
  85. } else {
  86. err.message = '连接服务器失败'
  87. }
  88. Message.error({
  89. message: err.message
  90. })
  91. // return Promise.resolve(err);
  92. return Promise.reject(err)
  93. }
  94. );
  95. /*
  96. * 封装get方法
  97. * @param url
  98. * @param data
  99. * @returns {Promise}
  100. */
  101. export function fetch(url,params={}){
  102. return new Promise((resolve,reject) => {
  103. axios.get(url,{
  104. params:params
  105. })
  106. .then(response => {
  107. resolve(response.data);
  108. })
  109. .catch(err => {
  110. reject(err)
  111. })
  112. })
  113. }
  114. /*
  115. * 封装post请求
  116. * @param url
  117. * @param data
  118. * @returns {Promise}
  119. */
  120. export function post(url,data = {}){
  121. return new Promise((resolve,reject) => {
  122. axios.post(url,data)
  123. .then(response => {
  124. resolve(response.data);
  125. },err => {
  126. reject(err)
  127. })
  128. })
  129. }
  130. /*
  131. * 封装patch请求
  132. * @param url
  133. * @param data
  134. * @returns {Promise}
  135. */
  136. export function patch(url,data = {}){
  137. return new Promise((resolve,reject) => {
  138. axios.patch(url,data)
  139. .then(response => {
  140. resolve(response.data);
  141. },err => {
  142. reject(err)
  143. })
  144. })
  145. }
  146. /*
  147. * 封装put请求
  148. * @param url
  149. * @param data
  150. * @returns {Promise}
  151. */
  152. export function put(url,data = {}){
  153. return new Promise((resolve,reject) => {
  154. axios.put(url,data)
  155. .then(response => {
  156. resolve(response.data);
  157. },err => {
  158. reject(err)
  159. })
  160. })
  161. }

数组方法

  1. export default class ArrayUtils {
  2. /**
  3. * 更新数组,若item已存在则将其从数组中删除,若不存在则将其添加到数组
  4. * **/
  5. static updateArray(array,item){
  6. for (var i = 0, len = array.length; i < len; i++) {
  7. var temp = array[i];
  8. if (item=== temp) {
  9. array.splice(i, 1);
  10. return;
  11. }
  12. }
  13. array.push(item);
  14. }
  15. /**
  16. * 判断两个数组的是否相等
  17. * @return boolean true 数组长度相等且对应元素相等
  18. * */
  19. static isEqual(arr1,arr2){
  20. if(!(arr1&&arr2))return false;
  21. if(arr1.length!=arr2.length)return false;
  22. for(let i=0,l=arr1.length;i<l;i++){
  23. if (arr1[i]!=arr2[i])return false;
  24. }
  25. return true;
  26. }
  27. /**
  28. * clone 数组
  29. * @return Array 新的数组
  30. * */
  31. static clone(from){
  32. if(!from)return [];
  33. let newArray=[];
  34. for(let i=0,l=from.length;i<l;i++){
  35. newArray[i]=from[i];
  36. }
  37. return newArray;
  38. }
  39. /**
  40. * 将数组中指定元素移除
  41. * **/
  42. static remove(array,item){
  43. if (!array)return;
  44. for(var i=0,l=array.length;i<l;i++){
  45. if (item===array[i])array.splice(i,1);
  46. }
  47. }
  48. }

数组是否相等

  1. Array.prototype.equals = function (array) {
  2. // if the other array is a falsy value, return
  3. if (!array)
  4. return false;
  5. // compare lengths - can save a lot of time
  6. if (this.length != array.length)
  7. return false;
  8. for (var i = 0, l = this.length; i < l; i++) {
  9. // Check if we have nested arrays
  10. if (this[i] instanceof Array && array[i] instanceof Array) {
  11. // recurse into the nested arrays
  12. if (!this[i].equals(array[i]))
  13. return false;
  14. }
  15. else if (this[i] != array[i]) {
  16. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  17. return false;
  18. }
  19. }
  20. return true;
  21. }

日期补0

  1. function p(s) {
  2. return s < 10 ? '0' + s: s;
  3. }
  4. //创建、格式化时间函数
  5. var younger_time = function(time) {
  6. var time = new Date(time);
  7. var year = time.getFullYear();
  8. var month = time.getMonth() + 1; // 月份是从0-11
  9. var day = time.getDate();
  10. //格式化时间
  11. var str = year + '-' + p(month) + '-' + p(day);
  12. //写入时间格式为 xxxx-xx-xx
  13. console.log(str);
  14. }

日期(当前时间与参数时间相差)

  1. function timestampFormat( timestamp ) {
  2. function zeroize( num ) {
  3. return (String(num).length == 1 ? '0' : '') + num;
  4. }
  5. var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
  6. var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
  7. var curDate = new Date( curTimestamp * 1000 ); // 当前时间日期对象
  8. var tmDate = new Date( timestamp * 1000 ); // 参数时间戳转换成的日期对象
  9. var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
  10. var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();
  11. if ( timestampDiff < 60 ) { // 一分钟以内
  12. return "刚刚";
  13. } else if( timestampDiff < 3600 ) { // 一小时前之内
  14. return Math.floor( timestampDiff / 60 ) + "分钟前";
  15. } else if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) {
  16. return '今天' + zeroize(H) + ':' + zeroize(i);
  17. } else {
  18. var newDate = new Date( (curTimestamp - 86400) * 1000 ); // 参数中的时间戳加一天转换成的日期对象
  19. if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
  20. return '昨天' + zeroize(H) + ':' + zeroize(i);
  21. } else if ( curDate.getFullYear() == Y ) {
  22. return zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
  23. } else {
  24. return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
  25. }
  26. }
  27. }
  1. export default function(time) {
  2. if (time == undefined) return ''
  3. let hours = parseInt(time / (60 * 60)),
  4. minutes = parseInt((time % (60 * 60)) / 60),
  5. seconds = parseInt(time % 60)
  6. return `${hours}小时${minutes}分钟${seconds}秒`
  7. }

回到顶部

  1. /**
  2. * 回到顶部
  3. * @return {[type]} [description]
  4. */
  5. scrollTop(){
  6. let timer = setInterval(() => {
  7. let top = document.body.scrollTop || document.documentElement.scrollTop;
  8. let speed = Math.ceil(top / 5);
  9. document.body.scrollTop = top - speed;
  10. if (top === 0) {
  11. clearInterval(timer);
  12. }
  13. }, 20)
  14. }

加载图片

  1. function loadImg(src){
  2. let promise = new Promise(function (resolve, reject) {
  3. let img = document.createElement('img')
  4. img.onload = function () {
  5. resolve(img)
  6. }
  7. img.onerror = function () {
  8. reject('图片加载失败')
  9. }
  10. img.src = src
  11. })
  12. return promise
  13. }

克隆

  1. export function deepClone(source) {
  2. if (!source && typeof source !== 'object') {
  3. throw new Error('error arguments', 'shallowClone')
  4. }
  5. const targetObj = source.constructor === Array ? [] : {}
  6. for (const keys in source) {
  7. if (source.hasOwnProperty(keys)) {
  8. if (source[keys] && typeof source[keys] === 'object') {
  9. targetObj[keys] = source[keys].constructor === Array ? [] : {}
  10. targetObj[keys] = deepClone(source[keys])
  11. } else {
  12. targetObj[keys] = source[keys]
  13. }
  14. }
  15. }
  16. return targetObj
  17. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注