从数组中获取n个随机元素,并在元素不足时创建重复元素

时间:2018-10-25 11:11:59

标签: javascript arrays random

我有对象数组,例如:

let array1 = [
{name: '1', image: '1.jpg'},
{name: '2', image: '2.jpg'},
{name: '3', image: '4.jpg'},
{name: '4', image: '5.jpg'},
];

我想从中获取n个随机元素,并找到用于此目的的函数:

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
 while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
return result
}

唯一的问题是,当我想拥有n> arr.length时,此方法不起作用。我想弄清楚在这种情况下如何增加元素数量。例如,重复其中已经存在的元素。

我尝试添加条件:

if(n > len) {
    arr.push(arr);
    console.log(arr);
}

但这对我没有好处,因为元素被作为另一个对象推送,而不是单独检查console.log:

0: {name: "1", image: "1.jpg"}
1: {name: "2", image: "2.jpg"}
2: {name: "3", image: "4.jpg"}
3: {name: "4", image: "5.jpg"}
4: Array(5)
0: {name: "1", image: "1.jpg"}
1: {name: "2", image: "2.jpg"}
2: {name: "3", image: "4.jpg"}
3: {name: "4", image: "5.jpg"}
4: (5) [{…}, {…}, {…}, {…}, Array(5)]
length: 5

我尝试过的其他方法均无效。如果有人能找到解决方法,我将非常感激。

/////////编辑-整个函数getRandom(arr,n):

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
       throw new RangeError("getRandom: more elements taken than available");
    while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }

    if (arr == warmUpAll) {
      document.getElementById("warmup").innerHTML = '<span class="exerciseheader">Warm Up - 10 minutes</span>' + "</br>" ;
    }
    else if (arr == legsAll){
      document.getElementById("legsDisplay").innerHTML = '<span class="exerciseheader">Legs</span>' + "</br>";
    }

    for (let i=0;i<result.length;i+=1) {
      let displayname = document.createTextNode(result[i].name);
      if (arr == warmUpAll) {
        source = './images/warmUp/' + result[i].image;
        warmUpSources.push(source);
        document.getElementById('warmup').appendChild(displayname);
        document.getElementById('warmup').appendChild(document.createElement("br" ));
      }
      else if (arr == armsAll) {
        source = './images/arms/' + result[i].image;
        armsSources.push(source);
        document.getElementById('armsDisplay').appendChild(displayname);
        document.getElementById('armsDisplay').appendChild(document.createElement("br" ));
      }
  }
}

1 个答案:

答案 0 :(得分:0)

当前,您的代码给出了额外括号的语法错误,并删除了该括号,但仅返回1个随机值。它显然没有循环。你可以试试这个

function fillArrayRandomly(array, n) {
let res = [];
while (res.length !== n) {
    let randomValue = array[Math.floor(Math.random() * array.length)];
    res.push(randomValue);
}
return res;}