2021-05-05 10:13:49 -07:00
---
id: 56533eb9ac21ba0edf2244b8
title: 用 += 運算符連接字符串
challengeType: 1
videoUrl: 'https://scrimba.com/c/cbQmmC4'
forumTopicId: 16803
dashedName: concatenating-strings-with-the-plus-equals-operator
---
# --description--
我們還可以使用 `+=` 運算符來< dfn > 拼接</ dfn > 字符串到現有字符串變量的結尾。 對於那些被分割成幾段的長的字符串來說,這一操作是非常有用的。
2021-05-10 01:12:02 +05:30
**提示:** 注意空格。 拼接操作不會在兩個字符串之間添加空格,所以,如果想要加上空格的話,你需要自己在字符串裏面添加。
2021-05-05 10:13:49 -07:00
例如:
```js
2021-10-27 15:10:57 +00:00
let ourStr = "I come first. ";
2021-05-05 10:13:49 -07:00
ourStr += "I come second.";
```
2021-06-30 20:47:19 +05:30
`ourStr` 的值爲字符串 `I come first. I come second.`
2021-05-05 10:13:49 -07:00
# --instructions--
2021-08-31 09:47:25 -07:00
使用 `+=` 操作符,多行合併字符串 `This is the first sentence.` 和 `This is the second sentence.` ,並賦值給 `myStr` 。 參照示例中顯示的方式使用 `+=` 操作符,並確保在兩個字符串之間包含一個空格。 先把第一個字符串賦值給 `myStr` ,然後拼接第二個字符串。
2021-05-05 10:13:49 -07:00
# --hints--
2021-06-30 20:47:19 +05:30
`myStr` 的值應該是字符串 `This is the first sentence. This is the second sentence.`
2021-05-05 10:13:49 -07:00
```js
assert(myStr === 'This is the first sentence. This is the second sentence.');
```
應該使用 `+=` 操作符創建 `myStr` 變量。
```js
assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));
```
# --seed--
## --after-user-code--
```js
(function(){
if(typeof myStr === 'string') {
return 'myStr = "' + myStr + '"';
} else {
return 'myStr is not a string';
}
})();
```
## --seed-contents--
```js
2021-10-27 15:10:57 +00:00
let myStr;
2021-05-05 10:13:49 -07:00
```
# --solutions--
```js
2021-10-27 15:10:57 +00:00
let myStr = "This is the first sentence. ";
2021-05-05 10:13:49 -07:00
myStr += "This is the second sentence.";
```