三个拆分示例是相关联的,结合使用。
1、范围随机
function randomFrom(lowerValue, upperValue) { return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue); }
2、数字拆分(包含随机排序)
/** *数字随机分割 * * @param {*} number * @param {*} count * @return {*} */ function randomFigure(number, count) { let arr = []; let num = number / count while (count > 0) { let res = count == 1 ? number : randomFrom(1, Math.floor(num)); arr.push(res); count--; number -= res; num = number / count } var len = arr.length; for (var i = 0; i < len - 1; i++) { var index = parseInt(Math.random() * (len - i)); var temp = arr[index]; arr[index] = arr[len - i - 1]; arr[len - i - 1] = temp; } return arr; }
3、数组随机拆分
/** *数组随机分割 * * @param {*} arr * @param {*} count * @return {*} */ function randomNumBoth(arr, count) { let newRandow = []; var splarr = randomFigure(arr.length, count) splarr.forEach(function (d, di) { let temarr = []; for (i = 0; i < d; i++) { temarr.push(arr[0]) arr.splice(0, 1); } newRandow.push(temarr); }) return newRandow; }