getRandomInt 总是返回 0

我正在使用developer.mozilla.com的功能


console.log(getRandomInt(1));


function getRandomInt(max) {

  return Math.floor(Math.random() * Math.floor(max));

}

我只需要它是 1 或 0。

如果我在 chrome 开发者控制台中调用上面的脚本,那么我总是得到“未定义”


http://img3.mukewang.com/6196438700017f7200120019.jpg

绝地无双
浏览 162回答 1
1回答

一只斗牛犬

这种行为背后的原因是Math.floor()。从文档:Math.floor() 函数返回小于或等于给定数字的最大整数。资料来源:Math.floor()您需要使用什么才能使其按照您的要求工作Math.round()。正如文档所述:Math.round() 函数返回四舍五入到最接近的整数的数字的值。来源:Math.round()请在下面找到这个例子:console.log(getRandomInt(1));function getRandomInt(max) {   const random = Math.random() * max;   return Math.round(random);}希望这可以帮助!添加:正如@Kaiido提到你有值的有源滤波器name。如果您删除它,您将看到该值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript