美文网首页大前端
Javascript常用小技巧

Javascript常用小技巧

作者: 天問_专注于大前端技术 | 来源:发表于2022-02-16 18:48 被阅读0次

收集汇总平时开发过程中的 Javascript 常用小技巧和方法。如:伪(类)数组转数组、获取数据类型、生成随机ID、日期时间格式化等等,将不定时补充更新。

Javascript

一、伪(类)数组转数组

日常类数组对象:

  • {0:1, 1:'abc', length:2}
  • DOM HTMLCollection对象 和 NodeList 对象
  • arguments对象
// 类数组
var ls = document.getElementsByName('span')
console.log(ls)

// 方法一
var li = Array.prototype.slice.apply(ls)
console.log(li)

// 方法二
var arr = [].slice.apply({0:1, 1:'abc', length:2})
console.log(arr)

// 方法三
var list = Array.from(ls)
console.log(list)

二、获取数据类型

借助 Object.prototype.toStringcall 封装方法

function getType(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1)
}

getType(NaN)      // Number
getType(null)     // Null
getType(undefined)// Undefined
getType(true)     // Boolean
getType(12)       // Number
getType('abc')    // String
getType([])       // Array
getType({})       // Object
getType(Date)     // Function
getType(Symbol)   // Function
getType(Promise)  // Function
getType(window)   // Window
getType(document) // HTMLDocument

三、生成随机ID

利用 Math.randomtoString 封装方法

function getUuid() {
  return Math.random().toString(36).toUpperCase().slice(2)
}

getUuid()   // AXDVJWW2P2G
getUuid()   // 69YB3NFCEM7
getUuid()   // H5JHQSSUEBL
getUuid()   // GVOI0V4KRMR

四、日期时间格式化

基于 Date 对象和 正则 封装方法

function formatFixedDate(date, fmt) {
  if (typeof date === 'number') {
    date = new Date(date);
  }
  if (!(date instanceof Date)) {
    return '';
  }
  if (typeof date === 'string') {
    date = date.includes('0+0000') ? date.substr(0, 19) : date;
  }
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  const week = {
    0: '日',
    1: '一',
    2: '二',
    3: '三',
    4: '四',
    5: '五',
    6: '六',
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length));
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '星期' : '周') : '') + week[`${date.getDay()}`]);
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((`00${o[k]}`).substr((`${o[k]}`).length)));
    }
  }
  return fmt;
}

formatFixedDate(Date.now(), 'yyyy-MM-dd HH:mm:ss')                  // 2022-02-16 18:01:14
formatFixedDate(new Date('2022-01-01'), 'yyyy年M月d日 HH:mm:ss')    // 2022年1月1日 08:00:00

欢迎访问:天问博客

相关文章

网友评论

    本文标题:Javascript常用小技巧

    本文链接:https://www.haomeiwen.com/subject/qqpdlrtx.html