JavaScript 从数组中删除随机项,然后将其从数组中删除,直到数组为空

javascriptweb developmentobject oriented programming更新于 2025/9/26 7:08:17

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

相关文章


有用资源