【问题标题】:How to randomly select 3 elements and remove them from the array?如何随机选择 3 个元素并将它们从数组中删除?
【发布时间】:2019-06-26 07:26:20
【问题描述】:

我需要一个函数来帮助我在一个数组中选择 3 个随机元素并将它们从数组中删除。

【问题讨论】:

  • 您可以先生成随机数,这些随机数是 0 到 array.length 范围内的整数,然后从数组中拼接它们。你试过什么?

标签: javascript arrays random


【解决方案1】:

只需从 Math.randomsplice 的数组中随机删除一个元素,并重复此操作 3 次:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

arr.splice(Math.floor(Math.random() * arr.length), 1);
arr.splice(Math.floor(Math.random() * arr.length), 1);
arr.splice(Math.floor(Math.random() * arr.length), 1);

console.log(arr);

【讨论】:

    【解决方案2】:

    这是一个简单的纯js方法... 你也可以使用 ecma 过滤器,但我选择了基本的。

    在同一条线上艰难地跑了 3 次让我觉得我内心的某些东西有点死了.....

    var array = [1,2,3,4,5,6,7,8,9];
    
    function removeRandomly(array, numberOfDeletions) {
        for(var i=0;i<numberOfDeletions;i++){
            array.splice(Math.floor(Math.random() * array.length), 1)
        }
        console.log(array)
    }
    
    removeRandomly(array, 3)

    【讨论】:

      【解决方案3】:

      我创建了一个递归函数,它接受一个数组并删除计数。另外,我更喜欢以不同的方式使用过滤器而不是拼接。

      function removeRandom(array, number) {
        const randomIndex = Math.floor(Math.random() * array.length);
        const result = array.filter(function(item) {
          return item !== array[randomIndex]
        });
        if (number > 1)
          return removeRandom(result, number - 1)
        else
          return result
      }
      const a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const result = removeRandom(a, 3)
      console.log(result)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        • 2018-10-20
        • 1970-01-01
        • 2014-02-28
        • 2014-07-23
        相关资源
        最近更新 更多