Skip to content

打乱数组

js
function shuffleArray(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1)); // 随机生成一个索引
    [arr[i], arr[j]] = [arr[j], arr[i]]; // 交换元素
  }
  return arr;
}

简单数组去重

js
const uniqueArray = (arr) => [...new Set(arr)];

去除空格

js
const noSpacesStr = (str) => str.replace(/\s+/g, '');

重新加载当前页面

js
location.reload();

滚动页面顶部

js
window.scrollTo(0, 0);

补零

js
function padZero(num, length) {
  return num.toString().padStart(length, '0');
}

字符串反转

js
const reversedStr = (str) => str.split('').reverse().join('');

深拷贝

js
function deepClone(origin, target) {
    var tar = target || {}
    var toStr = Object.prototype.toString
    var arrType = '[object Array]'
    for (var k in origin) {
        if (origin.hasOwnProperty(k)) {
            if (typeof origin[k] === 'object' && origin[k] !== null) {
                tar[k] = toStr.call(origin[k]) === arrType ? [] : {}
                deepClone(origin[k], tar[k])
            } else {
                tar[k] = origin[k]
            }
        }
    }
    return tar
}

防抖节流

js
function debounce(fn, delay) {
  let timeout;
  
  return function(...args) {
    clearTimeout(timeout); 
    timeout = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

function throttle(fn, delay) {
  let lastTime = 0;
  
  return function(...args) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      lastTime = now;
      fn.apply(this, args);
    }
  };
}