2.5 KiB
2.5 KiB
id, challengeType, videoUrl, forumTopicId, localeTitle
id | challengeType | videoUrl | forumTopicId | localeTitle |
---|---|---|---|---|
cf1111c1c12feddfaeb1bdef | 1 | https://scrimba.com/c/cRn6bfr | 18186 | 使用 JavaScript 生成随机整数 |
Description
- 用
Math.random()
生成一个随机小数。 - 把这个随机小数乘以
20
。 - 用
Math.floor()
向下取整 获得它最近的整数。
Math.random()
永远不会返回1
。同时因为我们是在用Math.floor()
向下取整,所以最终我们获得的结果不可能有20
。这确保了我们获得了一个在0到19之间的整数。
把操作连缀起来,代码类似于下面:
Math.floor(Math.random() * 20);
我们先调用Math.random()
,把它的结果乘以20,然后把上一步的结果传给Math.floor()
,最终通过向下取整获得最近的整数。
Instructions
0
到9
之间的随机整数。
Tests
tests:
- text: <code>myFunction</code>的结果应该是一个整数。
testString: assert(typeof randomWholeNum() === "number" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})());
- text: 需要使用<code>Math.random</code>生成随机数字。
testString: assert(code.match(/Math.random/g).length > 1);
- text: 你应该将<code>Math.random</code>的结果乘以 10 来生成 0 到 9 之间的随机数。
testString: assert(code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) || code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g));
- text: 你需要使用<code>Math.floor</code>移除数字中的小数部分。
testString: assert(code.match(/Math.floor/g).length > 1);
Challenge Seed
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
// Only change code below this line.
return Math.random();
}
After Test
(function(){return randomWholeNum();})();
Solution
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
return Math.floor(Math.random() * 10);
}