3.1 字符串的遍历器

字符串可以被for…of循环遍历

1
2
3
4
5
6
for (let codePoint of 'foo') {
console.log(codePoint)
}
// "f"
// "o"
// "o"

3.2 includes(), startsWith(), endsWith()

  • includes():返回布尔值,表示是否找到了参数字符串。
  • startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
    1
    2
    3
    4
    let s = 'Hello world!';
    s.startsWith('Hello') // true
    s.endsWith('!') // true
    s.includes('o') // true

3.3 repeat()

1
2
3
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""

3.4 模板字符串

如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中.如果不想要这个换行,可以使用trim方法消除它。
模板字符串中嵌入变量,需要将变量名写在${}之中。
传统的 JavaScript 语言,输出模板通常是这样写的

1
2
3
4
5
6
$('#result').append(
'There are <b>' + basket.count + '</b> ' +
'items in your basket, ' +
'<em>' + basket.onSale +
'</em> are on sale!'
);

ES6 引入了模板字符串解决这个问题

1
2
3
4
5
6
7
8
9
10
11
12
$('#result').append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);

//**消灭换行**
$('#result').append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`.trim());

字符串中嵌入变量

1
2
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

大括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象属性。

1
2
3
4
5
6
7
8
9
10
11
12
let x = 1;
let y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"

模板字符串之中还能调用函数。

1
2
3
4
5
6
function fn() {
return "Hello World";
}

`foo ${fn()} bar`
// foo Hello World bar