给我们一个字符串/数字文字数组。我们需要创建一个函数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