极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# 如何实现一个 sampleSize 函数,从数组中随机取 N 个元素

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 696 (opens new window)

const shuffle = (list) => list.sort((x, y) => Math.random() - 0.5);
const sampleSize = (list, n) => shuffle(list).slice(0, n);

Author

回答者: voezy (opens new window)

Array.prototype.sampleSie = function (size) {
  const result = [];
  const tmp = [...this];
  const len = tmp.length;
  for (let i = 0; i < size && i < len; i++) {
    const index = Math.floor(Math.random() * tmp.length);
    result[i] = tmp.splice(index, 1)[0];
  }
  return result;
};
Last Updated: 11/4/2022, 6:34:31 PM