js实现随机取数据

67 阅读1分钟

js的随机函数是Math.random(),返回一个在区间[0, 1)内的浮点数。

随机一个10以内的数(不包括10)

Math.random() * 10;

随机一个10以内的整数(不包括10)

Math.floor(Math.random() * 10);

随机一个10以内的整数包括10

Math.floor(Math.random() * 11);

随机一个区间值。

  1. 随机5-10之间的数,包括5,但不包括10
// [0, 5) + 5
Math.random() * 5 + 5
  1. 随机5-10之间的数,包括5和10。

    TODO 现在还没想到比较好的方式来实现。

随机一个区间整数

随机5-10之间的一个整数,包括5和10

Math.floor(Math.random() * 6) + 5

从list中随机取N条数据

function getRandomItems(list, n) {
  const newList = [...list];
  const items = [];
  for (let i = 0; i < n; i++) {
    // 随机一个index
    const randomIndex = Math.floor(Math.random() * list.length);
    // 取出该随机项,确保不会重复被选中
    const [randomItem] = newList.splice(randomIndex, 1);
    items.push(randomItem);
  }
  return items;
}