banner
{小朋友}

xiaopy

常用方法

  • 常用的工具函數

new Map#

new Map MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map

const map = new Map();
map.set("first",1);  // 輸出結構 Map(2) {'first' => 1}
map.has("first") // true 回去has表中查找有沒有一個鍵值是匹配有則 true 無則false
map.get("first") // 1 獲取到該鍵所對應的值 沒有返回undefined

/**
 * for of 方法迭代Map
 */
const map = new Map();
map.set(1,"one");
map.set(2,"two");
for (let [key,value] of map){ // 可以同時拿到key value
  console.log(key,value) // 1,one   2,two
}
for (let key of map.keys()){  // 只能拿到鍵值
  console.log(key) // 1  2
}

/**
 * 兩數之和的算法題
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
const twoSum = function(nums, target) {
    const map = new Map();
    for(let i = 0;i<nums.length;i++){
        if(map.has(target - nums[i])){
            return [map.get(target - nums[i]),i]
        }else{
            map.set(nums[i],i)
        }
    }
};

const nums = [2,4,5,7,10]

const target = 14

twoSum(nums,target) // [1,4]  輸出等於target值 各自數值的下標

字串數字反轉#

/**
 * @param {number} num
 * @return {boolean}
 */
const isPalindrome = function(num) {
  if (num === 0){
     return true;
  }
  const str = num + '';
  let result = '';
  for (let i = 0;i<str.length;i++){
    result += str[str.length-1-i];
  }
  if (str === result){
     return true;
  }else{
     return false;
  }
}

字串轉換 -(駝峰轉下劃線 / 下劃線轉駝峰)#

/**
 * 下劃線轉駝峰
 * @return
 */
const toHump = (result) => {
    return result.replace(/\_(\w)/g, function(_, res){
        return res.toUpperCase();
    });
}

/**
 * 駝峰轉換下劃線
 * @return
 */
const toUnderline = (result) => {
  return result.replace(/([A-Z])/g,"_$1").toLowerCase();
}

localStorage 操作#

class Catch {
    constructor(isLocal = true) {
      this.storage = isLocal ? localStorage : sessionStorage;
    }

    setItem(key, value) {
      if (typeof value === "object") value = JSON.stringify(value);
      this.storage.setItem(key, value);
    }

    getItem(key) {
      try {
          return JSON.parse(this.storage.getItem(key));
      } catch (err) {
          this.storage.getItem(key);
      }
    }

    removeItem(key) {
      this.storage.removeItem(key);
    }

    clear() {
      this.storage.clear();
    }

    key(index) {
      return this.storage.key(index);
    }

    length() {
      return this.storage.lenght;
    }
}

const localCache = new Catch();
const sessionCache = new Catch(false);

export { localCache, sessionCache };
/**
 * 獲取cookie
 * @return string
 */
const getCookie = (name) => {
    const strcookie = document.cookie;//獲取cookie字串
    const arrcookie = strcookie.split("; ");//分割
    for ( let i = 0; i < arrcookie.length; i++) {
        const arr = arrcookie[i].split("=");
        if (arr[0] == name){
            return arr[1];
        }
    }
    return "";
}

/**
 * 獲取所有cookie
 * @return string
 */
const print = () => {
    const strcookie = document.cookie;//獲取cookie字串
    const arrcookie = strcookie.split(";");//分割
    for ( let i = 0; i < arrcookie.length; i++) {
        const arr = arrcookie[i].split("=");
        console.log(arr[0] +"=" + arr[1]);
    }
}
const print = () => {
    return eval('({' + document.cookie.replaceAll('=', ":'").replaceAll(';', "',") + "'})");
}

/**
 * cookie 增刪改
 */
const cookieManager = {
  set(key, val) {
    //設置cookie方法
    const date = new Date(); //獲取當前時間
    const expiresDays = 1; // 1天
    date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000); //格式化為cookie識別的時間
    document.cookie = key + '=' + val + ';expires=' + date.toGMTString(); //設置cookie
    console.log(key + '=' + val + ';expires=' + date.toGMTString(),'val....')
  },
  get(key) {
    //獲取cookie方法
    /*獲取cookie參數*/
    const cookies = document.cookie.replace(/[ ]/g, ''); //獲取cookie,並且將獲得的cookie格式化,去掉空格字符
    const arrCookie = cookies.split(';'); //將獲得的cookie以"分號"為標識 將cookie保存到arrCookie的數組中
    let tips; //聲明變數tips
    for (let i = 0; i < arrCookie.length; i++) {
      //使用for循環查找cookie中的tips變數
      const arr = arrCookie[i].split('='); //將單條cookie用"等號"為標識,將單條cookie保存為arr數組
      if (key == arr[0]) {
        //匹配變數名稱,其中arr[0]是指的cookie名稱,如果該條變數為tips則執行判斷語句中的賦值操作
        tips = arr[1]; //將cookie的值賦給變數tips
        break; //終止for循環遍歷
      }
    }
    return tips;
  },
  del(key) {
    //刪除cookie方法
    const date = new Date(); //獲取當前時間
    date.setTime(date.getTime() - 10000); //將date設置為過去的時間
    document.cookie = key + '=v; expires =' + date.toGMTString(); //設置cookie
  },
};

節流防抖(測試用例)#

/**
 * 防抖
 */
const debounce = (fn, delay) => {
  let timer;
  return function () {
    const arg = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arg);
    }, delay);
  };
};


/**
 * 節流
 */
const throttle = (fn, delay) => {
  let timer;
  return function () {
    let _this = this;
    let args = arguments;
    if (timer) {
      return;
    }
    timer = setTimeout(function () {
      fn.apply(_this, args);
      timer = null;
    }, delay);
  };
};

/**
 * 時間戳節流
 */
function timestamThrottle(fn, delay) {
  let previous = 0;
  // 使用閉包返回一個函數並且用到閉包函數外面的變數previous
  return function () {
    let now = new Date();
    if (now - previous > delay) {
      fn.apply(this, arguments);
      previous = now;
    }
  };
}


/**
 * 測試用例 
 * 以防抖函數為例子
 */
const debounceFn = debounce((e) => {
  console.log(e);
}, 500); // 防抖函數
document.onmousemove = (e) => {
  debounceFn(e); // 給防抖函數傳參
};

監聽複製 / 剪切#

/**
 * 監聽複製
 */
(function () {
  document.addEventListener('copy', (e) => {
    const selection = document.getSelection();
    e.clipboardData.setData('text/plain', selection.toString().toUpperCase());
    e.preventDefault();
    e.stopPropagation();
    let copy = (e.clipboardData || window.clipboardData).getData('text/plain');
    copy = copy.replace(/style/gi, 'data-style');
    console.log(copy, 'copy');
  });
})();

/**
 * 監聽剪切
 */
(function () {
  document.addEventListener('cut', (e) => {
    const selection = document.getSelection();
    e.clipboardData.setData('text/plain', selection.toString().toUpperCase());
    document.getSelection().deleteFromDocument();
    e.preventDefault();
    e.stopPropagation();
    let cut = (e.clipboardData || window.clipboardData).getData('text/plain');
    cut = cut.replace(/style/gi, 'data-style');
    console.log(cut, 'cut');
  });
})();

遞歸#

/**
 * 返回當前數據所有父結構數據(包括自己)
 * @param list = []
 * @param id: number
 */
function getParentId(list, id) {
    for (let i in list) {
        if (list[i].value == id) {
            return [list[i]];
        }
        if (list[i].children) {
            let node = getParentId(list[i].children, id);
            if (node !== undefined) {
                return node.concat(list[i]);
            }
        }
    }
}






/**
 * 遞歸查找指定數據
 * @param list = []
 * @param id: number
 */
function getCurrent(list, id) {
    for (let o of list || []) {
        if (o.value == id) return o
        const o_ = getCurrent(o.children, id)
        if (o_) return o_
    }
}







// parentId 和 id 相同時變成id的子集數據
//初始數據
var data = [
  { id: 2, parentId: 1 },
  { id: 1 },
  { id: 3, parentId: 2 },
  { id: 5, parentId: 4 },
  { id: 4 },
];
//處理後的數據
/*[
    {
      id: 1,
      child: [{
          id: 2, 
          parentId: 1, 
          child: [{
              id: 3,
              parentId: 2
          }]
      }]
   },
    {id: 4, child: [{id: 5, parentId: 4}]},
  ]*/
function returnData(arr) {
  //初始沒有上級的數據和
  let parents = arr.filter((item) => !item.parentId);
  //初始有上級的數據和
  let childs = arr.filter((item) => item.parentId);
  //遞歸處理數據
  function newData(parents, childs) {
    parents.forEach((item) => {
      childs.forEach((child, childIndex) => {
        if (item.id === child.parentId) {
          let newChilds = JSON.parse(JSON.stringify(childs));
          newChilds.splice(childIndex, 1); //刪除已經存在的數據
          item.childs = item.childs ? item.childs.push(child) : [child];
          newData([child], newChilds);
        } else {
          return false;
        }
      });
    });
  }
  newData(parents, childs);
  return parents;
}
let a = [];
console.log((a = returnData(data)));







// 筛选/过滤
// 例子
const memberList = [
  {
    name: "研發部",
    member: [
      {
        name: "前端",
        member: [
          {
            name: "張三",
            age: 18,
            member: [],
          },
        ],
      },
      {
        name: "後端",
        member: [
          {
            name: "李四",
            age: 24,
            member: [],
          },
        ],
      },
    ],
  },
  {
    name: "市場部",
    member: [
      {
        name: "主管",
        member: [
          {
            name: "王五",
            age: 30,
            member: [],
          },
        ],
      },
      {
        name: "經理",
        member: [
          {
            name: "老六",
            age: 28,
            member: [],
          },
        ],
      },
    ],
  },
];

// 過濾 name 值 並以數組的形式返回
const getAllMember = (arr) => {
    let member = [];
    arr.forEach(item => {
        if (item.member && item.member.length) {
            member = [
                ...member,
                ...getAllMember(item.member)
            ]
        } else {
            member.push(item.name);
        }
    });
    return member;
}


// 篩選 age 小於 20 的數據
const filterMember = (key, data) => {
  const filterList = [];

  data.forEach((ele) => {
    const { member, ...other } = ele;

    if (member && member.length) {
      const currentEle = {
        member: [],
        ...other,
      };
      const result = filterMember(key, member);

      if (result.length) {
        currentEle.member = result;
        filterList.push(currentEle);
      }
    } else if (other.age > key) {
      filterList.push(other);
    }
  });
  return filterList;
};

監聽用戶是否打開 devtools 行為#

(function () {
    var devtools = {
      open: false,
      orientation: null,
    };
    var threshold = 160;
    var emitEvent = function (state, orientation) {
      window.dispatchEvent(
        new CustomEvent("devtoolschange", {
          detail: {
            open: state,
            orientation: orientation,
          },
        })
      );
    };
    clearTimer = setInterval(function () {
      var widthThreshold = window.outerWidth - window.innerWidth > threshold;
      var heightThreshold = window.outerHeight - window.innerHeight > threshold;
      var orientation = widthThreshold ? "vertical" : "horizontal";

      if (
        !(heightThreshold && widthThreshold) &&
        ((window.Firebug &&
          window.Firebug.chrome &&
          window.Firebug.chrome.isInitialized) ||
          widthThreshold ||
          heightThreshold)
      ) {
        if (!devtools.open || devtools.orientation !== orientation) {
          emitEvent(true, orientation);
        }
        devtools.open = true;
        devtools.orientation = orientation;
      } else {
        if (devtools.open) {
          emitEvent(false, null);
        }
        devtools.open = false;
        devtools.orientation = null;
      }
    }, 500);
    if (typeof module !== "undefined" && module.exports) {
      module.exports = devtools;
    } else {
      window.devtools = devtools;
    }
  })();
  
  windown.addEventListener("devtoolschange", function (e) {
     console.log(e.detail)
  });

監聽某個元素的實時變化#

/**
 * 監聽某個元素的實時變化
 */
export const ListeningTagAttribute = () => {
    setTimeout(() => {
      //選擇要監聽的元素
      const targetNode = document.getElementById('detail-content');
  
      // 創建一個觀察器實例並傳入回調函數
      const observer = new MutationObserver((mutationsList, observer) => {
        // 循環遍歷每個變化
        for (let mutation of mutationsList) {
          console.log(mutation, mutationsList)
          if (mutation.type === 'attributes') {
            console.log('屬性值已改變:', mutation.attributeName, mutation.target.getAttribute(mutation.attributeName));
          }
        }
      });
  
      // 配置觀察器選項
      const config = { attributes: true, childList: false, subtree: false };
      //傳入目標節點和觀察器的配置對象
      observer.observe(targetNode, config);
    }, 3000)
  }

對 URL 的解析 / 和對 URL 參數的字段替換處理#

/**
 * @param {string} url 地址 
 * @param {string} arg 需要替換的參數名稱
 * @param {any} arg_val 需要替換的參數
 * @returns 返回處理後的url
 */
function changeURLArg(url,arg,arg_val){ 
    let pattern=arg+'=([^&]*)'; 
    let replaceText=arg+'='+arg_val; 
    if(url.match(pattern)){ 
        let tmp='/('+ arg+'=)([^&]*)/gi'; 
        tmp=url.replace(eval(tmp),replaceText); 
        return tmp; 
    }else{ 
        if(url.match('[\?]')){ 
            return url+'&'+replaceText; 
        }else{ 
            return url+'?'+replaceText; 
        } 
    } 
    return url+'\n'+arg+'\n'+arg_val; 
}

// 解析成對象
function queryURLparams(url) {
    let obj = {}
    if (url.indexOf('?') < 0) return obj
    let arr = url.split('?')
    url = arr[1]
    let array = url.split('&')
    for (let i = 0; i < array.length; i++) {
        let arr2 = array[i]
        let arr3 = arr2.split('=')
        obj[arr3[0]] = arr3[1]
    }
    return obj
}


function queryURLparamsRegEs5(url) {
    let obj = {}
    let reg = /([^?=&]+)=([^?=&]+)/g
    url.replace(reg, function() {
        obj[arguments[1]] = arguments[2]
    })
    return obj
}


function queryURLparamsRegEs6(url) {
    let obj = {}
    let reg = /([^?=&]+)=([^?=&]+)/g
    url.replace(reg, (...arg) => {
        obj[arg[1]] = arg[2]
    })
    return obj
}



/**
 * @param {string} param 需要添加在url地址後面的參數
 * @returns 
 */
function addParameterToURL(param) {
    let _url = location.href;
    _url += (_url.split('?')[1] ? '&' : '?') + param;
    return _url;
}

UUID#

function UUID() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "-";
 
    var UUID = s.join("");
    return UUID;
}


function UUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });

}


function UUID() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}


function uuid2(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],i;
    radix = radix || chars.length;
 
    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        var r;
        
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
 
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
 
    return uuid.join('');
}

模糊搜索#

const listdata = [
    {
      id: 1,
      name: "哈囉",
    },
    {
      id: 2,
      name: "哈haha",
    },
    {
      id: 3,
      name: "xiaoyang囉",
    },
];

function fuzzyQuery(list, keyWord, arrtibute = "name") {
    const reg = new RegExp(keyWord);
    const arr = [];
    for (let i = 0; i < list.length; i++) {
    if (reg.test(list[i][arrtibute])) {
        arr.push(list[i]);
    }
    }
    return arr;
};

console.log(fuzzyQuery(listdata, "囉", "name")); // [{id: 1, name: '哈囉'}1: {id: 3, name: 'xiaoyang囉'}]

陣列扁平化#

const arr = [
  {
    id: 1,
    name: 'node-1',
  },
  {
    id: 2,
    name: 'node-2',
    children: [
      {
        id: 3,
        name: 'node-3',
      },
      {
        id: 4,
        name: 'node-4',
        children: [
          {
            id: 5,
            name: 'node-5',
          },
        ],
      },
    ],
  },
];

/**
 * 扁平化
 */
const result = arr.reduce(function (prev, current) {
  prev.push({
    id: current.id,
    name: current.name,
    parent: current.parentId,
  });
  current.children &&
    current.children.forEach((v) => {
      v.parentId = current.id;
      arguments.callee(prev, v);
    });
  return prev;
}, []);




const map = [
  {
    id: 1,
    name: 'ndoe-1',
    parentId: undefined,
  },
  {
    id: 2,
    name: 'ndoe-2',
    parentId: undefined,
  },
  {
    id: 3,
    name: 'ndoe-3',
    parentId: 2,
  },
  {
    id: 4,
    name: 'ndoe-4',
    parentId: 2,
  },
  {
    id: 5,
    name: 'ndoe-5',
    parentId: 4,
  },
];

/**
 * 扁平化轉樹結構
 */
const result = map.reduce(function (prev, current, i, arr) {
  current.children = a = arr.filter((v) => v.parentId === current.id);
  if (!current.parentId) {
    prev.push(current);
  }
  return prev;
}, []);





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



function flatMap(list = [], id: number) {
    return list.flatMap(({children, ...other}) => {
        return [other].concat(flatMap(children))
    })
}

去重#

// 陣列物件去重
const duplicateRemoval = edgesdata.filter((item) => !line.some((ele) => ele?.id === item?.id));

// 陣列去重 [1,2,1,2,1,3,3,3]
function duplicateRemoval(arr) {
	const res = new Map();
	return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
}

// 陣列去重 [1,2,1,2,1,3,3,3]
const duplicateRemoval = (arr) =>  [...new Set(arr)];

// 陣列去重合併相同數據
function handlerArrayMerge(value){
    const tempIds = [],newArrs = [];
    for(const item of value){
        if(!tempIds.includes(item.id)){
            tempIds.push(item.id);
            newArrs.push(item);
        }else{
            for(const ele of newArrs){
                if(ele.id === item.id){
                    ele.children = handlerArrayMerge(ele.children.concat(item.children));
                }
            }
        }
    }
    return newArrs;
}

正則校驗#

// 判斷字串是 html 格式
function isHtml(str) {
   return /<[a-z]+\d?(\s+[\w-]+=("[^"]*"|'[^']*'))*\s*\/?>|&#?\w+;/i.test(str);
}

對數字的處理#

const num = 12.34567;


// 保留2位小數,不四捨五入
Math.floor(num * 100) / 100 // 輸出結果為 12.34


// 保留2位小數,四捨五入
num.toFixed(2);             // 輸出結果為 12.35


//四捨五入保留2位小數(不夠位數,則用0替補)
function keepTwoDecimals(num) {
  let result = parseFloat(num);
  if (isNaN(result)) {
    // 參數不符合要求
    return false;
  }
  result = Math.round(num * 100) / 100;
  let rt = result.toString();
  let pos = rt.indexOf('.');
  if (pos < 0) {
    pos = rt.length;
    rt += '.';
  }
  while (rt.length <= pos + 2) {
    rt += '0';
  }
  return rt;
}

keepTwoDecimals(124);       // 輸出結果 124.00

定時器處理#

/**
 * 定時器計時、暫停、繼續
 */
class timerRecording {
  timerId = undefined;
  // 定義一個變數,用於記錄暫停時的時間
  pauseTime = 0;
  // 定義一個變數,用於記錄計時器開始時間
  startTime = 0;

  startTimer() {
    // 如果已經有計時器在運行,則直接返回
    if (this.timerId) {
      return;
    }

    // 記錄計時器開始時間
    this.startTime = Date.now();

    // 啟動計時器,每隔1秒執行一次回調函數
    this.timerId = setInterval(() => {
      // 計算已經經過的時間
      let elapsed = Date.now() - this.startTime + this.pauseTime;

      // 將已經經過的時間格式化為 HH:MM:SS 的形式
      // let hours = Math.floor(elapsed / (60 * 60 * 1000));
      // let minutes = Math.floor((elapsed - hours * 60 * 60 * 1000) / (60 * 1000));
      // let seconds = Math.floor((elapsed - hours * 60 * 60 * 1000 - minutes * 60 * 1000) / 1000);
      // let timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

      // 轉換成累加的秒
      let seconds = parseInt(elapsed / 1000);

      // 將格式化後的時間顯示在當前文章的標籤屬性上
      document
        .getElementById('detail-content')
        ?.setAttribute('data-time', seconds);
    }, 1000);
  }

  // 暫停計時器
  pauseTimer() {
    // 如果沒有計時器在運行,則直接返回
    if (!this.timerId) {
      return;
    }

    // 清除計時器
    clearInterval(this.timerId);

    // 記錄暫停時的時間
    this.pauseTime += Date.now() - this.startTime;

    // 清空計時器 ID
    this.timerId = null;
  }
  // 繼續計時器
  continueTimer() {
    // 如果已經有計時器在運行,則直接返回
    if (this.timerId) {
      return;
    }

    // 記錄計時器開始時間
    this.startTime = Date.now();

    // 啟動計時器,每隔1秒執行一次回調函數
    this.timerId = setInterval(() => {
      // 計算已經經過的時間
      let elapsed = Date.now() - this.startTime + this.pauseTime;

      // 將已經經過的時間格式化為 HH:MM:SS 的形式
      // let hours = Math.floor(elapsed / (60 * 60 * 1000));
      // let minutes = Math.floor((elapsed - hours * 60 * 60 * 1000) / (60 * 1000));
      // let seconds = Math.floor((elapsed - hours * 60 * 60 * 1000 - minutes * 60 * 1000) / 1000);
      // let timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

      // 轉換成累加的秒
      let seconds = parseInt(elapsed / 1000);

      // 將格式化後的時間顯示在當前文章的標籤屬性上
      document
        .getElementById('detail-content')
        ?.setAttribute('data-time', seconds);
    }, 1000);
  }
}

const timerRecord = new timerRecording();
export { timerRecord };

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。