欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

批量生成随机手机号码

最编程 2024-04-08 14:48:10
...

复制以下代码:

export function createRandomPhone(length = 1,like = '',likeType = 0) {
    // let numStarts = new Array("139", "138", "137", "136", "135", "134", "159", "158", "157", "150", "151", "152", "188", "187", "182", "183", "184", "178", "130", "131", "132", "156", "155", "186", "185", "176", "133", "153", "189", "180", "181", "177");
    const secondNum = [3,4,5,7,8],
        numberList = [];
    let number,numberHtml;
    const startNumber = ()=>{
        return `1${secondNum[parseInt(Math.random() * secondNum.length)]}${parseInt(Math.random() * 10)}`;
    }
    // 偏好号码必须是4位
    like = like.length === 4 ? like : '';
    let leftLength = 8,ranIndex,rightLength;
    
    for (let n = 0; n < length; n++) {
        number = startNumber();
        // 随机出当前的偏好数字组合在后8位中的下标,4个组合下标最大为4
        if(like){
            ranIndex = likeType == '1' ? Math.floor(Math.random() * 5) : 4;
            leftLength = ranIndex;
            rightLength = 8 - like.length - leftLength;
        }
        // 随机偏好数字左边的数字
        for (let j = 0; j < leftLength; j++) {
            number += Math.floor(Math.random() * 10)
        }
        numberHtml = number;
        if(like){
            // 加入偏好数字
            number += like;
            numberHtml += `<span style="color: red;">${like}</span>`
            // 随机偏好数字右边的数字
            for (let j = 0; j < rightLength; j++) {
                const num = Math.floor(Math.random() * 10);
                number += num;
                numberHtml += num;
            }
        }
        numberList.push({number,numberHtml})
    }
    return numberList;
}

使用:

/** 批量生成随机手机号
 * @length 生成的手机号个数
 * @like 偏好数字 4位
 * @likeType 偏好数字出现的位置 0尾号 1随机
*/
createRandomPhone(); -> [{numberHtml:'136803116256',number:'136803116256'}]
createRandomPhone(2); -> [{numberHtml:'18694166258',number:'18694166258'},{numberHtml:'15903731098',number:'15903731098'}]
createRandomPhone(10,'1314'); -> [{numberHtml:'1740840<span style="color: red;">1314</span>',number:'17408401314'},...]