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

1、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);
}

2、splice

temp_array.splice(arrIndex, 1),

删除temp_array中下标为arrIndex的那个元素

作者: 莯汐

出处: < http://www.cnblogs.com/Eileen-lu/>

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在页面明显位置给出原文链接。

原文地址:https://www.cnblogs.com/Eileen-lu/p/11887874.html