2018-10-10 22:03:03 +00:00
|
|
|
|
---
|
|
|
|
|
id: cf1111c1c11feddfaeb9bdef
|
2021-03-15 03:20:39 +00:00
|
|
|
|
title: 使用 JavaScript 生成随机分数
|
2018-10-10 22:03:03 +00:00
|
|
|
|
challengeType: 1
|
2020-04-29 10:29:13 +00:00
|
|
|
|
videoUrl: 'https://scrimba.com/c/cyWJJs3'
|
|
|
|
|
forumTopicId: 18185
|
2021-01-13 02:31:00 +00:00
|
|
|
|
dashedName: generate-random-fractions-with-javascript
|
2018-10-10 22:03:03 +00:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --description--
|
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
随机数非常适合用来创建随机行为。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
在 JavaScript 中,可以用 `Math.random()` 生成一个在`0`(包括 0)到 `1`(不包括 1)之间的随机小数, 因此 `Math.random()` 可能返回 `0`,但绝不会返回 `1`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
**提示:** [使用赋值运算符存储值](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator)这一节讲过,所有函数调用将在 `return` 执行之前结束,因此我们可以 `return`(返回)`Math.random()` 函数的值。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --instructions--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
更改 `randomFraction`,使其返回一个随机数而不是 `0`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --hints--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
`randomFraction` 应该返回一个随机数。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
|
assert(typeof randomFraction() === 'number');
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```
|
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
`randomFraction` 应该返回一个小数。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
|
assert((randomFraction() + '').match(/\./g));
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```
|
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
需要使用 `Math.random` 生成随机的小数。
|
2020-04-29 10:29:13 +00:00
|
|
|
|
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
|
assert(code.match(/Math\.random/g).length >= 0);
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```
|
2020-04-29 10:29:13 +00:00
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
# --seed--
|
|
|
|
|
|
|
|
|
|
## --after-user-code--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
(function(){return randomFraction();})();
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
function randomFraction() {
|
|
|
|
|
|
|
|
|
|
// Only change code below this line
|
|
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
|
|
// Only change code above this line
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --solutions--
|
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
```js
|
|
|
|
|
function randomFraction() {
|
|
|
|
|
return Math.random();
|
|
|
|
|
}
|
|
|
|
|
```
|