ES6语法部分-字符串
改进1:允许字符串直接用for循环遍历,这里要用for…of,而for…in获取的是每个字符串的下标
let str = 'hello word!'
for(let s of str) {
console.log(s)
}
// h e l l o W o r d !
for(let s in str) {
console.log(s)
}
// 0 1 2 3 4 5 6 7 8 9
字符串允许被当做数组一样使用,换句话说,我们可以用下标的方式获取字符串中某个位置的字符。
let str = 'hello word!'
for(let s in str) {
console.log(str[s])
}
// h e l l o W o r d !
改进2:允许用反引号进行一些简化的字符串定义
1、用``声明
let name = `zha`
2、可以直接换行
let info = `zha
ng
ooo`
3、变量拼接
let name = 'zhang'
let info = `woshi${name},18!`
改进3:提供了一些好用的API方法,比如字符串补齐
padStart:返回新的字符串,表示用参数字符串从头部补全原字符串
padEnd:返回新的字符串,表示参数字符串尾部补全元字符串
for (let i = 0;i < 20; i++) {
console.log(i.toString().padStart(2, 'a'))
}
// a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 10 11 12 ... 19
for (let i = 0;i < 20; i++) {
console.log(i.toString().padEnd(2, 'a'))
}
// 0a 1a 2a 3a 4a 5a 6a 7a 8a 9a 10 11 ... 19