目 录CONTENT

文章目录

js-代码简洁之路(三)

萧瑟
2023-02-28 / 0 评论 / 0 点赞 / 259 阅读 / 1,614 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2023-07-03,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

1、生成指定范围随机数

export const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

2、数字千分位分隔

export const format = (n) => {
    let num = n.toString();
    let len = num.length;
    if (len <= 3) {
        return num;
    } else {
        let temp = '';
        let remainder = len % 3;
        if (remainder > 0) { // 不是3的整数倍
            return num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g).join(',') + temp;
        } else { // 3的整数倍
            return num.slice(0, len).match(/\d{3}/g).join(',') + temp; 
        }
    }
}

3、数组乱序

export const arrScrambling = (arr) => {
    for (let i = 0; i < arr.length; i++) {
      const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
      [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
    }
    return arr;
}

4、数组扁平化

export const 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;
}

5、数组中获取随机数

export const sample = arr => arr[Math.floor(Math.random() * arr.length)];

6、生成随机字符串

export const randomString = (len) => {
    let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
    let strLen = chars.length;
    let randomStr = '';
    for (let i = 0; i < len; i++) {
        randomStr += chars.charAt(Math.floor(Math.random() * strLen));
    }
    return randomStr;
};

7、字符串首字母大写

export const fistLetterUpper = (str) => {
    return str.charAt(0).toUpperCase() + str.slice(1);
};

8、手机号中间四位变成*

export const telFormat = (tel) => {
  	tel = String(tel); 
    return tel.substr(0,3) + "****" + tel.substr(7);
};

9、驼峰命名转换成短横线命名

export const getKebabCase = (str) => {
    return str.replace(/[A-Z]/g, (item) => '-' + item.toLowerCase())
}

10、短横线命名转换成驼峰命名

export const getCamelCase = (str) => {
    return str.replace( /-([a-z])/g, (i, item) => item.toUpperCase())
}

weixin_white

0

评论区