JavaScript generate random numbers without repeating

后端 未结 4 1272
天涯浪人
天涯浪人 2021-01-03 11:04

I have some code where I have an array of x amount of items. In this case, videos, and I want to randomly call a video, however if the current video already called is the sa

4条回答
  •  攒了一身酷
    2021-01-03 11:40

    First of all, why do you wrap all those strings in Arrays? I dropped them in my solution below. Anyway, easiest and cleanest solution is to clone the Array, and drop the selected URL from the new Array.

    var videoLinks = [
        '',
        '',
        '',
        '',
        ''
    ];
    var temp = videoLinks.slice();
    
    function randomVideo(){
      var r = Math.floor(Math.random()*temp.length);
      return temp.splice(r, 1);
    }
    

提交回复
热议问题