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 生日开业蛋糕祝福语简短