JS - 常用函數

1. 生成隨機顏色
function getRandomColor() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
2.生成相近顏色
function sameColor(color: any, n: number) {
   let colorsArr = color.length === 6 ? color.match(/[\da-z]{2}/g) : color.match(/[\da-z]{1}/g);
   let newColor = '';
   for (let i = 0; i < colorsArr.length; i++) {
       colorsArr[i] = parseInt(colorsArr[i].length === 1 ? colorsArr[i] + colorsArr[i] : colorsArr[i], 16);
       newColor += Math.floor(colorsArr[i] + (Math.random() > 0.5 ? -1 : 1) * Math.random() * n).toString(16);
   }
   return newColor;
 }
3.獲取url參數

function getParam(name: any) {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return decodeURI(r[2]);
  return null;
}
4. 將數字轉成每隔3位加一個逗號

// 12345678 => 123,456,78
function addCommas(n: any) {
  let reg = /\.\d+/;
  let num = (parseInt(n) || 0).toString();
  let temp = reg.exec(num);
  // 獲取小數部分,不存在小數則獲取空字符串
  let decimal = temp && temp[0] ? temp[0] : '';
  // 獲取小數點位置,不存在小數位置則獲取字符串長度
  let decimalPointIndex = temp && temp.index ? temp.index : num.length;
  // 獲取整數部分
  let integerNum = num.slice(0, decimalPointIndex);
  let result = '';
  // 逗號分隔操作
  while (integerNum.length > 3) {
    result = ',' + integerNum.slice(-3) + result;
    integerNum = integerNum.slice(0, integerNum.length - 3);
  }
  // 不足3位直接加到最前面
  if (integerNum) {
    result = integerNum + result;
  }
  // 最後面加上小數部分
  result = result + decimal;
  return result;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章