JavaScript从数组中删除随机项,然后从数组中删除它,直到数组为空
给我们一个字符串/数字文字数组。我们需要创建一个函数removeRandom(),该函数接受数组并递归地从数组中删除一个随机项,并同时打印它直到数组包含项。
这可以通过使用Math.random()创建一个随机数,并使用Array.prototype.splice()删除该索引处的项并将其打印直到数组的长度缩小为0来完成。
这是执行相同操作的代码-
示例
const arr = ['Arsenal', 'Manchester United', 'Chelsea', 'Liverpool',
'Leicester City', 'Manchester City', 'Everton', 'Fulham', 'Cardiff City'];
const removeRandom = (array) => {
while(array.length){
const random = Math.floor(Math.random() * array.length);
const el = array.splice(random, 1)[0];
console.log(el);
}
};
removeRandom(arr);控制台中的输出可以是-
注–由于它是随机输出,因此每次可能会有所不同,因此这只是许多可能的输出之一。
输出结果
Leicester City Fulham Everton Chelsea Manchester City Liverpool Cardiff City Arsenal Manchester United
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短