50个实用 JavaScript有用的代码片段和trick

平时工作过程中可以用到的实用代码集棉。

1判断对象否为空

export const isEmpty = obj => {
    return Object.keys(obj).length === 0
}

2浮点数取整

const x = 123.4545;
x >> 0; // 123
~~x; // 123
x | 0; // 123
Math.floor(x); // 123

注意:前三种方法只适用于32个位整数,对于负数的处理上和Math.floor是不同的。

Math.floor(-12.53); // -13
-12.53 | 0; // -12

3生成6位数字验证码

// 方法一
('000000' + Math.floor(Math.random() *  999999)).slice(-6);

// 方法二
Math.random().toString().slice(-6);

// 方法三
Math.random().toFixed(6).slice(-6);

// 方法四
'' + Math.floor(Math.random() * 999999);

debounce方法

debounce()方法用来延迟执行函数。

ar debounce = function (func, threshold, execAsap) {
  var timeout;

  return function debounced() {
    var obj = this, args = arguments;
    function delayed() {
      if (!execAsap)
        func.apply(obj, args);
      timeout = null;
    };

    if (timeout)
      clearTimeout(timeout);
    else if (execAsap)
      func.apply(obj, args);

    timeout = setTimeout(delayed, threshold || 100);
  };
}

图片URL转base64

/**
 * 图片地址转 Base64
 * @param {String} url 图片地址
 */
function convertUrlToBase64(url) {
  return new Promise(function(resolve, reject) {
    const img = new Image()
    img.crossOrigin = 'Anonymous'
    img.src = url
    img.onload = function() {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, img.width, img.height)
      const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
      const dataURL = canvas.toDataURL('image/' + ext)
      const base64 = {
        dataURL: dataURL,
        type: 'image/' + ext,
        ext: ext
      }
      resolve(base64)
    }
  })
}

Base64 转 Blob

/**
 * Base64 转 Blob
 * @param {String} base64 Base64源
 */
function convertBase64UrlToBlob(base64) {
  const parts = base64.dataURL.split(';base64,')
  const contentType = parts[0].split(':')[1]
  const raw = window.atob(parts[1])
  const rawLength = raw.length
  const uInt8Array = new Uint8Array(rawLength)
  for (let i = 0; i < rawLength; i++) {
    uInt8Array[i] = raw.charCodeAt(i)
  }
  return new Blob([uInt8Array], { type: contentType })
}

splice 删除修正

splice操作数组时会改变原数组,特别是循环中删除数据时,容易出现问题。

for (let i = 0; i < list.length; i++) {
  if (/** 条件 */) {
    // 逻辑
    i--;
  }
}

// 或者
for (let i = list.length; i >= 0; i--) {
  if (/** 条件 */) {
    // 逻辑
  }
}

// 使用双循环删除
for (var i = 0; i < arr.length; i++) {
  for (var j = i + 1; j < arr.length; j++) {
    if (arr[i] === arr[j]) {
      arr.splice(j, 1);
      j--;
    }
  }
}

简单深拷贝

/**
 * 符合JSON规范数据的深拷贝,日期格式要求为 `xxxx-xx-xx xx:xx:xx`
 * @param obj 数据源
 * @returns {any}
 */
export const clone = (obj) => {
    const regExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}\d{2}\.\d{3}Z$/
    return JSON.parse(JSON.stringify(obj), function (k, v) {
        if (typeof v === 'string' && regExp.test(v)) {
            return new Date(v)
        }
        return v
    })
}

延迟执行 Promise

/**
 * 异步延迟执行
 * @param t 时间毫秒数
 * @param v 执行函数
 * @returns {Promise<any>}
 */
export const delay = (t, v) => {
    return new Promise(function (resolve) {
        setTimeout(resolve.bind(null, v), t)
    })
}

统计文字个数

function wordCount(data) {
  var pattern = /[a-zA-Z0-9_\u0392-\u03c9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;
  var m = data.match(pattern);
  var count = 0;
  if( m === null ) return count;
  for (var i = 0; i < m.length; i++) {
    if (m[i].charCodeAt(0) >= 0x4E00) {
      count += m[i].length;
    } else {
      count += 1;
    }
  }
  return count;
}

var text = '贷款买房,也意味着你能给自己的资产加杠杆,能够撬动更多的钱,来孳生更多的财务性收入。';
wordCount(text); // 38

日期格式化

// 方法一
function format1(x, y) {
  var z = {
    y: x.getFullYear(),
    M: x.getMonth() + 1,
    d: x.getDate(),
    h: x.getHours(),
    m: x.getMinutes(),
    s: x.getSeconds()
  };
  return y.replace(/(y+|M+|d+|h+|m+|s+)/g, function(v) {
    return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-(v.length > 2 ? v.length : 2))
  });
}

format1(new Date(), 'yy-M-d h:m:s'); // 17-10-14 22:14:41

// 方法二
Date.prototype.format = function (fmt) { 
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "h+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)){
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  } 
  for (var 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;
}

new Date().format('yy-M-d h:m:s'); // 17-10-14 22:18:17

计算相对时间

 * 计算相对时间
 * @param {number} stamp 时间缀
 */
export const timeAgo = (stamp) => {
    const minute = 1000 * 60
    const hour = minute * 60
    const day = hour * 24
    const week = day * 7
    const month = day * 30
    const now = new Date().getTime()
    const difftime = now - stamp

    if (difftime < 0) return
    const minuteDiff = difftime / minute
    const hourDiff = difftime / hour
    const dayDiff = difftime / day
    const weekDiff = difftime / week
    const monthDiff = difftime / month

    if (monthDiff >= 1 && monthDiff < 3) {
        return `${parseInt(monthDiff)}月前`
    } else if (weekDiff >= 1 && weekDiff < 4) {
        return `${parseInt(weekDiff)}周前`
    } else if (dayDiff >= 1 && dayDiff < 6) {
        return `${parseInt(dayDiff)}天前`
    } else if (hourDiff >= 1 && hourDiff < 24) {
        return `${parseInt(hourDiff)}小时前`
    } else if (minuteDiff >= 1 && minuteDiff < 59) {
        return `${parseInt(minuteDiff)}分钟前`
    } else if (difftime >= 0 && difftime <= minute) {
        return '刚刚'
    }
}

在线网址
https://segmentfault.com/a/1190000011557368?utm_source=sf-similar-article#item-5

posted @ 2023-08-17 20:09  打个大大西瓜  阅读(24)  评论(0)    收藏  举报