var random = { /**获取两个数之间的随机小数(fixed是有效数字位数)*/ getDecimal(max, min, fixed=0) { return (Math.random() * (max - min) + min).toFixed(fixed); }, /**获取两个数之间的随机整数*/ getInteger(a, b) { return this.getDecimal(a, b, 1); }, /**返回a到b且包含a和b的随机整数(其中a,b不能为负数)*/ get(a, b) { return this.getInteger(a, b); }, /**获取数组中的随机一个元素*/ valueFromArray(arr) { if (arr && arr.length > 0) { return arr[random.get(arr.length - 1)]; } else { return arr; } }, /* 随机排序数组 */ sortArray: arr => arr.sort(() => Math.random() - 0.5), /*获取数组中的随机多个元素组成的数组*/ arrayFromArray(arr, data) { var tempArr = arr.concat(); data.randomTotal || (data.randomTotal = 0);//0代表获取任意多个随机元素,>0代表获取randomTotal个随机元素 data.startIndex || (data.startIndex = 0);//从数组开头随机的索引值 data.startIndex < 0 && (data.startIndex = 0); data.endIndex || (data.endIndex = arr.length);//随机截止到尾部的索引值 data.endIndex <= data.startIndex && (data.endIndex = data.startIndex + 1); data.endIndex > arr.length && (data.endIndex = arr.length); data.isContinue || (data.isContinue = false);//是否获取连续随机元素 data.isRepeat || (data.isRepeat = false);//是否获取重复的元素 if (data.isContinue) { var startIndex = data.randomTotal ? this.get(0, data.endIndex ? data.endIndex : tempArr.length - data.randomTotal) : this.get(0, tempArr.length); startIndex < data.startIndex && (startIndex = data.startIndex); var endIndex = data.randomTotal ? startIndex + data.randomTotal : this.get(startIndex, tempArr.length); endIndex > data.endIndex && (endIndex = data.endIndex); return tempArr.slice(startIndex, endIndex); } else { var newArr = []; for (var i = 0, len = data.randomTotal || tempArr.length; i < len; i++) { var randomIndex = this.get(data.startIndex > tempArr.length ? tempArr.length - 1 : data.startIndex, data.endIndex > tempArr.length - 1 ? tempArr.length - 1 : data.endIndex); newArr.push(tempArr[randomIndex]); data.isRepeat || tempArr.splice(randomIndex, 1); } return newArr; } } }; //测试用例 console.log(random.arrayFromArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], { randomTotal: 3, startIndex: 0, endIndex: 10, isContinue: true, isRepeat: false }));