js 实用函数方法

动画函数
  function animate(duration) {
    const startTime = Date.now();
    const endTime = startTime + duration;

    function step() {
      const currentTime = Date.now();
      // const progress = (endTime - currentTime) / duration; // 1-0
      const progress = (currentTime - startTime) / duration; // 0-1

      if (currentTime < endTime) {
        requestAnimationFrame(step.bind(null, progress));
      } else {
        console.log('over');
      }
    }
    step();
  }

  animate(300);
百分比数据分化
	function percentage(source, n = 0) {
      var arr = JSON.parse(JSON.stringify(source));
      var product = [];
      var total = 0;
      for (var i = 0; i < arr.length; i++) {
        total += arr[i];
      }
      for (var i = 0; i < arr.length; i++) {
        var val = (arr[i] / total * 100).toFixed(n);
        val = parseFloat(val)
        product.push(val);
      }
      return product;
    }
// 第二个值是保留小数位 返回 => 数组数字类型 单位需要拼接
percentage([30, 30, 40, 90], 1); // [15.8, 15.8, 21.1, 47.4] => ['15.8%', '15.8%', '21.1%', '47.4']
轮子
	父节点 parentNode
	子节点 childNodes
	第一个子节点 firstChild
	最后一个子节点 lastChild
	前一个兄弟 previousSibling
	后一个兄弟 nextSibling

如何得到前面的所有兄弟节点 
function getPrevs(o){
    var arr = [];
    while(o = o.previousSibling){
        if(o.nodeType == 1){
            arr.push(o);
        }
    }
    return arr;
}

如何得到后面的所有兄弟节点 
function getNexts(o){
    var arr = [];
    while(o = o.nextSibling){
        if(o.nodeType == 1){
            arr.push(o);
        }
    }
    return arr;
}

如何得到所有兄弟:
function getAllSiblings(o){
    var arr = [];
    var os = o.parentNode.childNodes;
    for(var i = 0 ; i < os.length ; i++){
        if(os[i].nodeType == 1 && o != os[i]){
            arr.push(os[i]);
        }
    }
    return arr;
}

十位值取整
	Math_Integer(base) {
      const q = Math.floor((base / 10)) * 10;
      const w = base % 10;
      const e = Math.ceil((w / 10)) * 10;
      const r = q + e;
      return r <= 0 ? 0 : r < 10 ? 10 : r ;
    }
// 第二个值是保留小数位
Math_Integer(87); // 90
Math_Integer(40); // 40
Math_Integer(1); // 10
Math_Integer(0); // 0
时间格式化
 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+)/i.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, reg => String(this.getFullYear()).substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, reg => reg.length === 1 ? o[k] : (("00" + o[k]).substr(String(o[k]).length)));
    }
  }
  return fmt;
}

// 挂载在date原型上的时间格式化
new Date().Format("YYYY-MM-DD hh:mm:ss.S") // 2025-12-30 13:44:30.373 精确到毫秒

const OS = Object.prototype.toString;

function isDate(obj) {
   return OS.call(obj) === '[object Date]';
}
function isString(obj) {
   return OS.call(obj) === '[object String]';
}
function getClass(el) {
   return el.getAttribute('class') || el.getAttribute('className');
}
// 获取平年闰年 平年为True
Date.isLeap = function(y) {
   return (y % 100 !== 0 && y % 4 === 0) || (y % 400 === 0);
};
// 判断两者两者时间是否是相同 年月日 返回值boolean
Date.prototype.isSame = function(y, m, d) {
    if (isDate(y)) {
         var dt = y;
         y = dt.getFullYear();
         m = dt.getMonth() + 1;
         d = dt.getDate();
     }
     return this.getFullYear() === y && this.getMonth() + 1 === m && this.getDate() === d;
 }
// 给Date添加天
Date.prototype.add = function(n) {
     this.setDate(this.getDate() + n);
     return this;
 }
// 给Date扣除天
Date.prototype.minus = function(n) {
   this.setDate(this.getDate() - n);
}
// 获取年月的天数
Date.getDaysNum = function(y, m) {
     var num = 31;
     switch (m) {
         case 2:
             num = this.isLeap(y) ? 29 : 28;
             break;
         case 4:
         case 6:
         case 9:
         case 11:
             num = 30;
             break;
     }
     return num;
 }
 Date.getDaysNum(2025, 12) // 31
 // 三个参数,年月 和需要添加的月的个数
Date.getSiblingsMonth = function(y, m, n) {
    var d = new Date(y, m - 1);
    d.setMonth(m - 1 + n);
    return {
        y: d.getFullYear(),
        m: d.getMonth() + 1
    };
  //  return new Date(d.getFullYear(), d.getMonth() + 1)
}
Date.getSiblingsMonth(2025, 11, 3) // { y: 2026, m: 2 }
// 三个参数,年月 和需要添加的月的个数 n 默认为1 可不传
Date.getNextMonth = function(y, m, n) {
    return this.getSiblingsMonth(y, m, n || 1);
}
console.dir(Date.getNextMonth(2025, 5, 8)); // // { y: 2026, m: 1 }

// 三个参数,年月 和需要扣除的月的个数
Date.getPrevMonth = function(y, m, n) {
    return this.getSiblingsMonth(y, m, 0 - (n || 1));
}
console.dir(Date.getPrevMonth(2025, 5, 1));	// { y: 2025, m: 4 }
数组洗牌
// 1)
function shuffle(arr) {
  for (let i=arr.length;i;i--){
   let j = Math.floor(Math.random() * i);
   [arr[i-1],arr[j]] = [arr[j],arr[i-1]];    
  }
  return arr;
}
// 2)

function shuffle(arr) {
  return arr.sort(() => Math.random() > 0.5 ? -1: 1);
}

function sample(arr){
    var result = [];
    var idxArr = [];
    while(result.length != n){
        var idx = ~~(Math.random() * arr.length);
        if (!idxArr.includes(idx)){
            result.push(arr[idx]);
            idxArr.push(idx);
        }
    }
    return result;
}

  // 冒泡排序
  function sort(arr) {
    arr.forEach((v, i) => {
      arr.forEach((vv, ii) => { 
        if (arr[i] < arr[ii + i]) {
          let temp = arr[i];
          arr[i] = arr[ii + i];
          arr[ii + i] = temp;
        }
      })
    })
    return arr;
  }
function quicksort(arr) {
        if (arr.length <= 1) return arr;
        var pivot = arr[0];
        var big = [];
        var small = [];
        for (let i = 1; i < arr.length; i++) {
          if (arr[i] > pivot) {
            big.push(arr[i]);
          } else {
            small.push(arr[i]);
          }
        }
        return [...quicksort(small), pivot, ...quicksort(big)]
      }
// 数组扁平化
var arr = [[[[1,2,3],4,5],6],7,[[[8]],9,10]];

function flatten(arr) {
 var result = [];
  function iterator(arr) {
    for (let i = 0; i < arr.length; i++) {
      if (Array.isArray(arr[i])) {
        iterator(arr[i]);
      } else {
        result.push(arr[i]);
      }
    }
  }
  iterator(arr);
  return result;
}


console.log(flatten(arr));

// 原生遍历
// filter
Array.prototype.filter = function(fn){
    var result = [];
    for(var i = 0 ; i < this.length ; i++){
        if(fn(this[i])){
            result.push(this[i]);
        }
    }
    return result;
}
// map
Array.prototype.map = function(fn){
    var result = [];
    for(var i = 0 ; i < this.length ; i++){
        result.push(fn(this[i]));
    }
    return result;
}


var arr = [1,2,3,4,5,6,7];
console.log(arr.filter(item => item % 2 == 0));

var arr = [1,2,3,4,5,6,7];
console.log(arr.map(item => item * 2));

// 查询字符串 and 反查询字符串
  queryStr(obj) {
    let r = [];
    for (let i in obj) r.push(obj[i] + '=' + i);
    return r.join('&');
  },
  reQueryStr(str) {
    let r = str.split('&');
    let o = {};
    for (let i = 0; i < r.length; i++) {
      let key = r[i].split('=')[0];
      let val = r[i].split('=')[1];
      o[key] = val;
    };
    return o;
  }
vscode使用正则匹配出所有控制台打印: ^.*(console.log).*\n
// 浏览器控制台查看页面启动时间
performance.timing.loadEventEnd -performance.timing.navigationStart
// 创建指定数量的数组
Array.apply(null, { length: 10 }).map((_, i) => i);
Array.from({length: 10}, (_, i) => i)

利用git bash 创建公钥和私钥小方法
	openssl genrsa -out private.pem 1024	创建私钥
	openssl rsa -in private.pem -pubout -out public.pem  创建公钥
NPM ----快速删除node_modules
npm install rimraf -g
rimraf node_modules
匹配 console.log 和被注释的 console.log
(\/\/(\s?)+)?console\.log\(.*\);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值