欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript常用工具函数库汇总

程序员文章站 2022-04-11 13:06:05
对象或数组的深拷贝/** * 对象或数组的深拷贝 * @param {*} cloneobj 被克隆的对象 * @param {*} targetobj 克隆的目标对象 * @param {*} is...

对象或数组的深拷贝

/**
 * 对象或数组的深拷贝
 * @param {*} cloneobj 被克隆的对象
 * @param {*} targetobj 克隆的目标对象
 * @param {*} isoverride 若属性重复,是否覆盖被克隆对象的属性
 */
function deepclone(cloneobj, targetobj, isoverride = true) {
  const _tostring = object.prototype.tostring
  if (_tostring.call(cloneobj) !== '[object array]' && _tostring.call(cloneobj) !== '[object object]') {
    return cloneobj
  }
  var clonetarget = _tostring.call(cloneobj) === '[object array]' ? [] : {}
  for (let key in cloneobj) {
    if (object.prototype.hasownproperty.call(cloneobj, key)) {
      if (_tostring.call(cloneobj[key]) === '[object array]' || _tostring.call(cloneobj[key]) === '[object object]') {
        clonetarget[key] = deepclone(cloneobj[key])
      } else {
        clonetarget[key] = cloneobj[key]
      }
    }
  }
  if (targetobj && (_tostring.call(cloneobj) === _tostring.call(targetobj))) {
    //这里要注意,克隆的目标对象也要deepclone下
    clonetarget = isoverride
      ? object.assign(clonetarget, deepclone(targetobj))
      : object.assign(deepclone(targetobj), clonetarget)
  }
  return clonetarget
}

精准判断数据类型

//精准判断数据类型
function getverifydatatypes() {
  const types = ["string", "number", "boolean", "null", "undefined", "function", "object", "array", "date", "error", "regexp", "symbol", "map", "set"]
  let type = {}
  // 示例用法:type.isstring('javascript')
  for (let i = 0; i < types.length; i++) {
    type[`is${types[i]}`] = obj => object.prototype.tostring.call(obj) === `[object ${types[i]}]`
  }
  // 判断字符串是否为json格式
  type.isjsonstr = str => {
    if (typeof str == 'string') {
      try {
        let obj = json.parse(str);
        if (obj && typeof obj == 'object') {
          return true;
        }
        return false;
      } catch (e) {
        return false;
      }
    } else {
      return false;
    }
  }
  return type
}

日期格式化

/**
 * 日期格式化
 * @param {*} date 日期对象
 * @param {*} beforehyphen 年月日连字符
 * @param {*} afterhyphen 时分秒连字符
 */
function formatdate(date = new date(), beforehyphen = '-', afterhyphen = ':') {
  const formatnumber = n => {
    n = n.tostring()
    return n[1] ? n : `0${n}`
  }
  const year = date.getfullyear()
  const month = date.getmonth() + 1
  const day = date.getdate()
  const hour = date.gethours()
  const minute = date.getminutes()
  const second = date.getseconds()
  const ymd = [year, month, day].map(formatnumber).join(beforehyphen)
  const hms = [hour, minute, second].map(formatnumber).join(afterhyphen)
  return `${ymd} ${hms}`
}

把时间戳转换为剩余的天、时、分、秒

/**
 * 把时间戳转换为剩余的天、时、分、秒,一般应用于倒计时场景中
 * @param {*} timestamp 时间戳
 */
function convertimestamp(timestamp) {
  const formatnumber = n => {
    n = n.tostring()
    return n[1] ? n : `0${n}`
  }
  let day = math.floor((timestamp / 1000 / 3600) / 24);
  let hour = math.floor((timestamp / 1000 / 3600) % 24);
  let minute = math.floor((timestamp / 1000 / 60) % 60);
  let second = math.floor(timestamp / 1000 % 60);
  return {
   day: day,
   hour: formatnumber(hour),
   minute: formatnumber(minute),
   second: formatnumber(second)
  }
}

从数组中随机取出一项

// 从数组中随机取出一项
function getrandomitembyarray(items) {
  return items[math.floor(math.random() * items.length)];
}

将有父子关系的数组转换成树形结构数据

let data = [
  { parentid: 0, id: 1, value: 'xxx' },
  { parentid: 1, id: 3, value: 'xxx' },
  { parentid: 4, id: 6, value: 'xxx' },
  { parentid: 3, id: 5, value: 'xxx' },
  { parentid: 2, id: 4, value: 'xxx' },
  { parentid: 1, id: 2, value: 'xxx' },
]

// 转换为树形array结构
function totreeary(arr, pid = 0) {
  return arr
    .filter(({ parentid }) => parentid === pid)
    .map(a => ({
      ...a,
      children: totreeary(arr.filter(({ parentid }) => parentid !== pid), a.id)
    }))
}

// 转换为树形object结构
function totreeobj(arr, pid = 0) {
  let res = {}
  arr.filter(({ parentid }) => parentid === pid)
    .foreach(a => {
      res[a.id] = {
        ...a,
        children: totreeobj(arr.filter(({ parentid }) => parentid !== pid), a.id)
      }
    })
  return res
}

console.log(totreeary(data))
console.log(totreeobj(data))

生成随机字符串

// 随机字符串
const randomstr = () => {
  return new date().gettime() + '-' + math.random().tostring(36).substr(2)
}

过滤html标签

// 过滤html标签
const filterhtmltag = (str) => {
  str = str.replace(/<\/?[^>]*>/g, ''); //去除html tag
  str = str.replace(/[|]*\n/, '') //去除行尾空格
  str = str.replace(/&npsp;/ig, ''); //去掉npsp
  return str;
}

以上就是javascript常用工具函数库汇总的详细内容,更多关于javascript工具函数库的资料请关注其它相关文章!