由于您没有指定数组的最小数量或每个数组的最小/最大元素,这里有一个通用函数,您可以为每个数组指定最小/最大元素。请注意,尽管这并没有严格执行 min 元素,实际上可能不可能 100% 做到这一点,这取决于原始数组中有多少元素与随机分配给每个数组元素的数量。例如,如果您有 10 个原始元素并且您执行 min 2 max 4,那么您最终可能会得到 3/3/3/1,因为 min 将被强制执行,直到没有足够的强制执行。你并没有真正给出任何“规则”。
min 和max 都是可选的,默认为1。如果只指定min,max 将默认为min。
还请注意,由于数组是通过引用传递的,因此默认情况下这将“清空”原始数组。如果您想保留原始数组,请取消注释函数中的第一行(如果您选择原型,则显然不适用)。
function randChunkSplit(arr,min,max) {
// uncomment this line if you don't want the original array to be affected
// var arr = arr.slice();
var arrs = [],size=1;
var min=min||1;
var max=max||min||1;
while (arr.length > 0) {
size = Math.min(max,Math.floor((Math.random()*max)+min));
arrs.push(arr.splice(0, size));
}
return arrs;
}
示例
var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
// randChunkSplit(letters)
[["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"], ["m"], ["n"], ["o"], ["p"], ["q"], ["r"], ["s"], ["t"], ["u"], ["v"], ["w"], ["x"], ["y"], ["z"]]
// randChunkSplit(letters,3)
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"], ["m", "n", "o"], ["p", "q", "r"], ["s", "t", "u"], ["v", "w", "x"], ["y", "z"]]
// randChunkSplit(letters,1,3)
[["a"], ["b", "c"], ["d", "e"], ["f", "g", "h"], ["i", "j", "k"], ["l"], ["m"], ["n", "o"], ["p", "q"], ["r"], ["s", "t"], ["u", "v", "w"], ["x", "y", "z"]]
// randChunkSplit(letters,2,3)
[["a", "b", "c"], ["d", "e", "f"], ["g", "h"], ["i", "j", "k"], ["l", "m", "n"], ["o", "p", "q"], ["r", "s", "t"], ["u", "v", "w"], ["x", "y", "z"]]
// randChunkSplit(letters,2,3)
// same thing as before, but notice how this time we end up with just 1 elem left over
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"], ["m", "n", "o"], ["p", "q"], ["r", "s"], ["t", "u", "v"], ["w", "x", "y"], ["z"]]
或者,您可以根据需要将其原型化为 Array,如下所示:
Array.prototype.randChunkSplit = function (min,max) {
var arrs = [],size=1;
var min=min||1;
var max=max||min||1;
while (this.length > 0) {
size = Math.min(max,Math.floor((Math.random()*max)+min));
arrs.push(this.splice(0, size));
}
return arrs;
}
var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
letters.randChunkSplit(1,4)