助力你的工做效率, 封裝一些經常使用的工具函數(一)

爲了提升之後本身的工做效率,今天抽取了一些公共函數,但願你們能夠一塊兒總結!後續我會陸陸續續更新工具函數node

輸入一個值,返回其數據類型

function dataType(data) {
  return Object.prototype.toString.call(data)
}
複製代碼

數據去重

function unique(arr) {
    return [...new Set(arr)]
}

複製代碼

字符串去重

String.prototype.unique = function () {
    var obj = {},
    str = '',
    len = this.length;
    for (var i = 0; i < len; i++) {
      if (!obj[this[i]]) {
        str += this[i];
        obj[this[i]] = true;
      }
    }
    return str;
}

去除連續的字符串

function unique(str) {
    return str.replace(/(\w)\1+/g, '$1')
}
複製代碼

reverse底層原理和擴展

Array.prototype.reverse = function () {
    var len = this.length;
    for (var i = 0; i < len; i++) {
        var temp = this[i];
        this[i] = this[len - 1 - i];
        this[len - 1 - i] = temp;
    }
    return this;
}
複製代碼

聖盃模式的繼承

function inherit(Target, Origin) {
    function F() {};
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    Target.prototype.constructor = Target;
    // 最終的原型指向
    Target.prop.uber = Origin.prototype;
}

複製代碼

找出字符串中第一次只出現一次的字母

String.prototype.firstAppear = function () {
    var obj = {},
        len = this.length;
    for (var i = 0; i < len; i++) {
        if (obj[this[i]]) {
            obj[this[i]]++;
        } else {
            obj[this[i]] = 1;
        }
    }
  for (var prop in obj) {

    if (obj[prop] == 1) {
        return prop;
    }
  }
}

複製代碼

找元素的第n級父元素

function parents(ele, n) {
  while (ele && n) {
      ele = ele.parentElement ? ele.parentElement : ele.parentNode;
      n--;
  }
  return ele;
}
複製代碼

判斷元素有沒有子元素

function hasChildren(e) {
    var children = e.childNodes,
        len = children.length;
    for (var i = 0; i < len; i++) {
        if (children[i].nodeType === 1) {
            return true;
        }
    }
    return false;
}
複製代碼

獲取url中的參數

function getWindonHref() {
    var sHref = window.location.href;
    var args = sHref.split('?');
    if (args[0] === sHref) {
        return '';
    }
    var hrefarr = args[1].split('#')[0].split('&');
    var obj = {};
    for (var i = 0; i < hrefarr.length; i++) {
        hrefarr[i] = hrefarr[i].split('=');
        obj[hrefarr[i][0]] = hrefarr[i][1];
    }
    return obj;
}

複製代碼

cookie管理

var cookie = {
    set: function (name, value, time) {
        document.cookie = name + '=' + value + '; max-age=' + time;
        return this;
    },
    remove: function (name) {
        return this.setCookie(name, '', -1);
    },
    get: function (name, callback) {
        var allCookieArr = document.cookie.split('; ');
        for (var i = 0; i < allCookieArr.length; i++) {
            var itemCookieArr = allCookieArr[i].split('=');
            if (itemCookieArr[0] === name) {
                return itemCookieArr[1]
            }
        }
        return undefined;
    }
}
複製代碼

防抖

function debounce(handle, delay) {
    var timer = null;
    return function () {
      var _self = this,
      _args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function () {
          handle.apply(_self, _args)
      }, delay)
    }
}
複製代碼

節流

function throttle(handler, wait) {
    var lastTime = 0;
    return function (e) {
      var nowTime = new Date().getTime();
      if (nowTime - lastTime > wait) {
        handler.apply(this, arguments);
        lastTime = nowTime;
      }
    }
}
複製代碼

函數柯里化

function curryIt(fn) {
  var length = fn.length,
      args = [];
  var result = function (arg) {
    args.push(arg);
    length--;
    if (length <= 0) {
        return fn.apply(this, args);
    } else {
        return result;
    }
  }
  return result
}
複製代碼

動態設置微信的title

function setTitle (title) {
  document.title = title
  let userAgent = window.navigator.userAgent.toLowerCase()
  let isiOS = userAgent.indexOf('applewebkit') >= 0
  let isWechat = userAgent.indexOf('micromessenger') >= 0
  if (isiOS && isWechat) {
    let iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    document.body.appendChild(iframe)
    iframe.onload = function () {
      setTimeout(function () {
        iframe.remove()
      }, 0)
    }
  }
}

複製代碼

判斷移動端的設備

function device () {
  let isType = false
  const u = navigator.userAgent
  if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
    isType = false
  } else if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    isType = true
  }
  return isType
}
複製代碼

localStorage設值、獲取值、移除和清空

save(key, item) {
  window.localStorage.setItem(key, JSON.stringify(item))
},
fetch(key) {
  let localStorage = window.localStorage.getItem(key)
  return localStorage ? JSON.parse(localStorage) : null
},
remove(key) {
  window.localStorage.removeItem(key)
},
clear() {
  window.localStorage.clear()
}
複製代碼

日期函數的處理

function(val, format) {
  var deFormat, formateDate, month, year, date, hours, mins, seconds
  var formats = {
    LLLL: function() {
      return `${year}${month}${date}${hours}:${mins}`
    },
    LLL: function() {
      return `${year}${month}${date}日`
    },
    llll: function() {
      return `${year}.${month}.${date}  ${hours}:${mins}`
    },
    lll: function() {
      return `${year}.${month}.${date}`
    },
    LL: function() {
      return `${month}${date}日`
    },
    mm: function() {
      return `${hours}:${mins}`
    },
    Lll: function() {
      return `${year}-${month}-${date}`
    },
    Llls: function() {
      return `${year}/${month}/${date}`
    },
    Lllss: function() {
      return `${year}/${month}/${date} ${hours}:${mins}:${seconds}`
    },
    Lllmm: function() {
      return `${year}-${month}-${date}  ${hours}:${mins}`
    }
  }
  if (!val && typeof val !== 'number') {
    return ''
  }
  deFormat = format || 'LLL'
  formateDate = new Date(val)
  year = formateDate.getFullYear()

  function changeDate(val) {
    var str = '00'
    if (val !== undefined && val !== null) {
      str = val.toString()
      str = str.length < 2 ? `0${str}` : str
    }
    return str
  }

  month = changeDate(formateDate.getMonth() + 1)
  date = changeDate(formateDate.getDate())
  hours = changeDate(formateDate.getHours())
  mins = changeDate(formateDate.getMinutes())
  seconds = changeDate(formateDate.getSeconds())
  return formats[deFormat]()
})
複製代碼
相關文章
相關標籤/搜索