2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
id: bd7123c9c450eddfaeb5bdef
|
2021-03-15 03:20:39 +00:00
|
|
|
title: 使用方括号查找字符串中的第 N 个字符
|
2018-10-10 22:03:03 +00:00
|
|
|
challengeType: 1
|
2020-04-29 10:29:13 +00:00
|
|
|
videoUrl: 'https://scrimba.com/c/cWPVJua'
|
|
|
|
forumTopicId: 18343
|
2021-01-13 02:31:00 +00:00
|
|
|
dashedName: use-bracket-notation-to-find-the-nth-character-in-a-string
|
2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --description--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
你也可以使用方括号( <dfn>bracket notation</dfn>)来获得一个字符串中的其他位置的字符。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
请记住,程序是从 `0` 开始计数,所以获取第一个字符实际上是第零个字符串。
|
2021-02-06 04:42:36 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
例如:
|
2021-02-06 04:42:36 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
var firstName = "Ada";
|
2021-03-15 03:20:39 +00:00
|
|
|
var secondLetterOfFirstName = firstName[1];
|
2021-02-06 04:42:36 +00:00
|
|
|
```
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
`secondLetterOfFirstName` 值应该为字符串 `d`。
|
|
|
|
|
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
|
|
|
让我们使用方括号,把 `lastName` 变量的第三个字符赋值给 `thirdLetterOfLastName`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
**提示:** 如果卡住了,请尝试查看上面的示例。
|
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
|
|
|
`thirdLetterOfLastName` 变量值应该为 `v` 。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
assert(thirdLetterOfLastName === 'v');
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
应该使用方括号表示法。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --after-user-code--
|
|
|
|
|
|
|
|
```js
|
|
|
|
(function(v){return v;})(thirdLetterOfLastName);
|
|
|
|
```
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
// Setup
|
|
|
|
var lastName = "Lovelace";
|
|
|
|
|
|
|
|
// Only change code below this line
|
|
|
|
var thirdLetterOfLastName = lastName; // Change this line
|
|
|
|
```
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --solutions--
|
2020-04-29 10:29:13 +00:00
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
```js
|
|
|
|
var lastName = "Lovelace";
|
|
|
|
var thirdLetterOfLastName = lastName[2];
|
|
|
|
```
|