2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 587d7b7e367417b2b2512b23
|
2020-12-16 00:37:30 -07:00
|
|
|
title: 使用 parseInt 函数
|
2018-10-10 18:03:03 -04:00
|
|
|
challengeType: 1
|
2020-04-29 18:29:13 +08:00
|
|
|
videoUrl: 'https://scrimba.com/c/cm83LSW'
|
|
|
|
forumTopicId: 301183
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: use-the-parseint-function
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --description--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`parseInt()`函数解析一个字符串返回一个整数下面是一个示例:
|
|
|
|
|
|
|
|
`var a = parseInt("007");`
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
上面的函数把字符串 "007" 转换成数字 7。 如果字符串参数的第一个字符是字符串类型的,结果将不会转换成数字,而是返回`NaN`.
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
在`convertToInteger`函数中使用`parseInt()`将字符串`str`转换为正数并返回。
|
|
|
|
|
|
|
|
# --hints--
|
|
|
|
|
|
|
|
`convertToInteger`应该使用`parseInt()`函数。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(/parseInt/g.test(code));
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`convertToInteger("56")`应该返回一个数字。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(typeof convertToInteger('56') === 'number');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`convertToInteger("56")`应该返回 56。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(convertToInteger('56') === 56);
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`convertToInteger("77")`应该返回 77。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(convertToInteger('77') === 77);
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`convertToInteger("JamesBond")`应该返回 NaN。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert.isNaN(convertToInteger('JamesBond'));
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-04-29 18:29:13 +08:00
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
function convertToInteger(str) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
convertToInteger("56");
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
```js
|
|
|
|
function convertToInteger(str) {
|
|
|
|
return parseInt(str);
|
|
|
|
}
|
|
|
|
```
|