开发记录

JavaScript——JavaScript相关问题记录,持续更行...

1、【代码优化】每条判断语句中包含多个可满足的条件 优化前

1
2
3
4
5
6
7
8
9
10
function foo(value){
    if(value === 1 || value === 2 || value === 3 || value === 4){
        toDoA(param);
    }else if(value === 5 || value === 6 || value === 7){
        toDoB(param);
    }else if(value === 8){
        toDoC(param);
    }
};
foo(3);

优化后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const obj = {
    '1,2,3,4': (param) => {
        toDoA();
    },
    '5,6,7': (param) => {
        toDoB(param);
    },
    '8': (param) => {
        toDoC(param);
    }
};
function foo(value){
    const key = Object.keys(obj).find(item => item.split(',').includes(value));
    obj[key](param)
};
foo(3);

2、【代码功能】获取URL参数

1
2
3
4
5
/**********URLSearchParams 方法**********/
// 创建一个URLSearchParams实例
const urlSearchParams = new URLSearchParams(window.location.search);
// 把键值对列表转换为一个对象
const params = Object.fromEntries(urlSearchParams.entries());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**********split 方法**********/
function getParams(url) {
  const res = {}
  if (url.includes('?')) {
    const str = url.split('?')[1]
    const arr = str.split('&')
    arr.forEach(item => {
      const key = item.split('=')[0]
      const val = item.split('=')[1]
      res[key] = decodeURIComponent(val) // 解码
    })
  }
  return res
}

3、【代码功能】实现金钱格式化

1
2
var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
1
2
3
4
5
function formatCash(str) {
   return str.split('').reverse().reduce((prev, next, index) => {
        return ((index % 3) ? next : (next + ',')) + prev
   })
}

4、【代码功能】toLocaleString用于返回格式化对象后的字符串 参考链接


5、【代码功能】检查对象是否为空

1
2
3
4
5
6
7
//Reflect.ownKeys()
//返回对象所有的key值,如果长度为0则对象为空(通过该方法可以获取到对象可枚举值和不可枚举值,但无法获取到对象的继承属性)
const isEmpty = obj => Reflect.ownKeys(obj).length === 0;

//Object.keys()
//返回对象所有的key值,如果长度为0则对象为空(通过该方法可以获取到对象所有的可枚举值,无法获取到不可枚举值和对象的继承属性)
const isEmpty = obj => Object.keys(obj).length === 0;

6、【代码功能】生成随机十六进制

1
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`

7、【代码功能】检查设备类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const judgeDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

judgeDeviceType()  // PC | Mobile

const judgeAgent = () => {
  let ua = navigator.userAgent,
      isWindowsPhone = /(?:Windows Phone)/.test(ua),
      isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
      isAndroid = /(?:Android)/.test(ua),
      isFireFox = /(?:Firefox)/.test(ua),
      isChrome = /(?:Chrome|CriOS)/.test(ua),
      isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
      isPhone = /(?:iPhone)/.test(ua) && !isTablet,
      isPc = !isPhone && !isAndroid && !isSymbian;
      console.log(ua);
  return {
    isTablet: isTablet, //平板
    isPhone: isPhone, //手机(苹果)
    isAndroid: isAndroid, //手机(安卓)
    isPc: isPc, //PC
  };
}

参考链接 参考链接


7、【代码功能】检查变量类型

1
const type = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase();


-->