Math.floor(Math.random() * array.length)

走远了吗. 提交于 2019-12-04 23:19:27

Math.floor(Math.random() * array.length) 

返回长度内的索引

eg:

changeLimit () {
  function getArrayItems(arr, num) {
    const temp_array = [];
    for(let index in arr) {
      temp_array.push(arr[index]);
    }
    const return_array = [];
    for (let i = 0; i<num; i++) {
      if(temp_array.length>0) {
        const arrIndex = Math.floor(Math.random()*temp_array.length);
        return_array[i] = temp_array[arrIndex];
        temp_array.splice(arrIndex, 1);
      } else {
        break;
      }
    }
    return return_array;
  }
  this.randomMovieList = getArrayItems(this.movieList, 5);
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!