代码实现
数字无重复版
//arr为提供好的数组,maxNum为取出随机数的个数
let arr = [1,2,3,4,5,6]
function randomNumArr(arr, maxNum) {
let numArr = [];
if(maxNum > arr.length){
return "指定的长度不能大于原数组的长度"
}
for (let i = 0; i < maxNum; i++) {
let number = Math.floor(Math.random() * arr.length); //生成随机数,为数组的下标
numArr.push(arr[number]); //往新建的数组里面传入这个数
arr.splice(number, 1); //传入后从原数组删除这个数,避免重复
}
return numArr
}
console.log(randomNumArr(arr,6))
//输出:[3, 4, 2, 5, 1, 6]
数字可重复版
//arr为提供好的数组,maxNum为取出随机数的个数
let arr = [1,2,3,4,5,6]
function randomNumArr(arr, maxNum) {
let numArr = [];
for (let i = 0; i < maxNum; i++) {
let number = Math.floor(Math.random() * arr.length); //生成随机数,为数组的下标
numArr.push(arr[number]); //往新建的数组里面传入这个数
}
return numArr
}
console.log(randomNumArr(arr,8))
//输出:[3, 6, 1, 5, 1, 1, 2, 5]
数组长度可随机
//arr为提供好的数组
let arr = [1,2,3,4,5,6]
let numArr = [];
let maxNum = Math.floor(Math.random() * arr.length + 1)
for (let i = 0; i < maxNum; i++) {
let number = Math.floor(Math.random() * arr.length)
numArr.push(arr[number])
arr.splice(number,1)
}
console.log(numArr)
必备知识
建议多从MDN developer.mozilla.org/zh-CN/ 网站上查阅知识
Math.floor() 函数总是返回小于等于一个给定数字的最大整数。
console.log(Math.floor(5.95));
// 输出: 5
console.log(Math.floor(5.05));
// 输出: 5
console.log(Math.floor(5));
// 输出: 5
console.log(Math.floor(-5.05));
// 输出: -6
Math.random() 函数返回一个浮点数,这个浮点数是大于等于 0,小于 1 之间的随机数,然后您可以缩放到所需的范围。实现将初始种子选择到随机数生成算法;它不能被用户选择或重置。
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
console.log(getRandomInt(3));
// 输出: 0 或 1 或 2
console.log(getRandomInt(1));
// 输出: 0
console.log(Math.random());
// 输出: 从 0 到 1 的随机数
push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
// 输出: 4
console.log(animals);
// 输出: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// 输出: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
// 输出: 4
console.log(animals);
// 输出: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// 输出: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(-2, 1);
// 运算后的 myFish: ["angel", "clown", "sturgeon"]
// 被删除的元素:["mandarin"]
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]