js方法

105 阅读1分钟

如何在JavaScript中将一个数字拆分为最多100个的块

/**
 * 平均分割成多段
 * @param count 总数
 * @param num   每段数量
 */
const chunkByArray = (count: number, num: number = 10000) => {
    console.log(count, num)

    let chunks = new Array(Math.floor(count / num)).fill(num)
    let remainder = count % num
    if (remainder > 0) {
        chunks.push(remainder)
    }

    return chunks
}

获取当天凌晨00:00:00到当前时间的时分秒长度

const selectType = ref(2), //1表示时,2表示分,3表示秒
    setInterDelay = {
        3: {
            time: 1000,
        },
        2: {
            time: 60 * 1000,
        },
        1: {
            time: 60 * 60 * 1000,
        },
    }

const getYCount = () => {
    const { time } = setInterDelay[selectType.value]
    let currentDay = date.value !== moment().format('YYYY-MM-DD'), //是否是当天时间
        startDate = date.value + ' 00:00:00', //开始时间
        endDate = currentDay ? date.value + ' 23:59:59' : new Date(), //结束时间
        countTimeCha = new Date(startDate).getTime() - new Date(endDate).getTime(), //开始时间和结束时间毫秒差
        countDelay = Math.abs(countTimeCha / time).toFixed(), //根据秒分时,确定x轴的时间长度
        count = currentDay ? Number(countDelay) : Number(countDelay) - 1 //当天时间取上一 秒分时,过去的时间取全部
    return count;
}

获取随机数

/**
 * 获取随机数
 * @param idx
 */
const getXTime = (idx: number) => {
    let baseValue = Math.random() * 1000
    let smallBaseValue = 0
    function next(idx: number) {
        smallBaseValue = idx % 30 === 0 ? Math.random() * 700 : smallBaseValue + Math.random() * 500 - 250
        baseValue += Math.random() * 20 - 10
        return Math.max(0, Math.round(baseValue + smallBaseValue) + 3000)
    }
    return next(idx).toFixed(2)
}
Math.random()
Math.random().toString().slice(2, 6)