2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: bd7123c9c452eddfaeb5bdef
|
2021-03-14 21:20:39 -06:00
|
|
|
title: 使用方括号查找字符串中的倒数第 N 个字符
|
2018-10-10 18:03:03 -04:00
|
|
|
challengeType: 1
|
2020-04-29 18:29:13 +08:00
|
|
|
videoUrl: 'https://scrimba.com/c/cw4vkh9'
|
|
|
|
forumTopicId: 18344
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string
|
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
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
我们既可以获取字符串的最后一个字符,也可以用获取字符串的倒数第 N 个字符。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2021-11-06 08:56:52 -07:00
|
|
|
例如,你可以使用 `firstName[firstName.length - 3]` 获取 `const firstName = "Augusta"` 字符串的倒数第三个字母的值
|
2021-02-06 04:42:36 +00:00
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
例如:
|
2021-02-06 04:42:36 +00:00
|
|
|
|
|
|
|
```js
|
2021-11-06 08:56:52 -07:00
|
|
|
const firstName = "Augusta";
|
|
|
|
const thirdToLastLetter = firstName[firstName.length - 3];
|
2021-02-06 04:42:36 +00:00
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2021-06-14 23:47:03 +09:00
|
|
|
`thirdToLastLetter` 的值应该为字符串 `s`。
|
2021-03-14 21:20:39 -06:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
使用方括号( <dfn>bracket notation</dfn>)来获得 `lastName` 字符串中的倒数第二个字符。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
**提示:** 如果卡住了,请尝试查看上面的示例。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --hints--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
`secondToLastLetterOfLastName` 应该是字母 `c`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(secondToLastLetterOfLastName === 'c');
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
您应该使用 `.length` 获取倒数第二个字母。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```js
|
2021-02-06 04:42:36 +00:00
|
|
|
assert(code.match(/\.length/g).length > 0);
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --after-user-code--
|
|
|
|
|
|
|
|
```js
|
|
|
|
(function(v){return v;})(secondToLastLetterOfLastName);
|
|
|
|
```
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
// Setup
|
2021-11-06 08:56:52 -07:00
|
|
|
const lastName = "Lovelace";
|
2021-01-13 03:31:00 +01:00
|
|
|
|
|
|
|
// Only change code below this line
|
2021-11-06 08:56:52 -07:00
|
|
|
const secondToLastLetterOfLastName = lastName; // Change this line
|
2021-01-13 03:31:00 +01:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
2020-04-29 18:29:13 +08:00
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
```js
|
2021-11-06 08:56:52 -07:00
|
|
|
const lastName = "Lovelace";
|
|
|
|
const secondToLastLetterOfLastName = lastName[lastName.length - 2];
|
2021-01-13 03:31:00 +01:00
|
|
|
```
|