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

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

Issue

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

function sample(arr){ const index = Math.floor(Math.random() * arr.length ) return arr[index] }

Array.prototype.sample = function () {
  if (!Array.isArray(this)) {
    throw new Error("not a Array");
  }

  return this[Math.floor(Math.random() * this.length)];
};
function random(n, m) {
  var result = Math.random() * (m + 1 - n) + n;
  while (result > m) {
    result = Math.random() * (m + 1 - n) + n;
  }
  return Math.round(result);
}

Array.prototype.sample = function () {
  if (!Array.isArray(this)) {
    throw new Error("not a Array");
  }

  return this[random(0, this.length - 1)];
};

Math.random() 函数返回一个浮点, 伪随机数在范围从 0 到小于 1,用数学表示就是 [0, 1),可以利用它来实现 sample 函数

Array.prototype.sample = function () {
  return this[Math.floor(Math.random() * this.length)];
};

Author

回答者: tangli06 (opens new window)

Math.random() 函数返回一个浮点, 伪随机数在范围从 0 到小于 1,用数学表示就是 [0, 1),可以利用它来实现 sample 函数 Array.prototype.sample = function() { return this[Math.floor(Math.random()*this.length)] }; @shfshanyue 调用时箭头函数 this 不是指向调用数组,写成普通函数有效

@tangli06 大意了

Last Updated: 11/27/2021, 6:11:48 PM