1.includes(), startsWith(), endsWith()
在ES5中我们判断一个字符串是否包含在另一个字符串的方法是indexOf,如果值为-1则不包含,否则返回该字符串对应的索引。
var str_1 = 'hello es6' console.log(str_1.indexOf('h')) //0 var str_1 = 'hello es6' console.log(str_1.indexOf('5')) //-1
在ES6中又新增了3个方法includes(), startsWith(), endsWith(),这三个方法均返回布尔值,同时都支持第二个参数,代表开始搜索的位置,我们依次看下其作用:
(1) includes() 它是判断字符串中是否包含某个字符串,包含为true,否则false,第二个参数(index)表示的是从第index个位置直到字符串结束。
str_1.includes('ell') // true str_1.includes('ell',1) // true str_1.includes('ell',2) // false
(2) startsWith()用来判断参数字符串是否在源字符串的头部,第二个参数(index)表示的是从第index个位置直到字符串结束。
str_1.startsWith('h',0) // true str_1.startsWith('e',0) // false str_1.startsWith('e',1) // true
(3)endsWith()用来判断参数字符串是否在源字符串的尾部。但是它接收的第二个参数(index)与前两个方法不同,他是针对源字符串的前index个字符。
str_1.endsWith('es6',str_1.length-1) // false str_1.endsWith('es6',str_1.length) // true str_1.endsWith('he',2) // true
2.repeat(n)
方法返回一个新字符串,表示将原字符串重复n
次,同时该参数可为浮点数,选择向下取整Math.floor();如果参数是
负数,在(0~-1)之间则视为0,否则报错;如果repeat
的参数是字符串,则会先转换成数字;
str_1.repeat(2) // "hello es6hello es6" str_1.repeat(2.9) // "hello es6hello es6" str_1.repeat(-0.1) // "" str_1.repeat('a') // "" str_1.repeat('1') // "hello es6"
3.模板字符串
在项目开发中,列表渲染十分普遍,同时一般情况下我们都是先写好静态页面,等请求到数据,遍历数据渲染时把写好的html代码粘贴到js中,然后去补充字符 ’,进行''+变量+’‘去填充,这种ES5的方式去输出模板,让人觉得恶心。
var listhtml = '' res.data.list.forEach(function(el,ind){ listhtml += '<li>'+ '<img src="'+el.src+'">'+ ' <span>''+el.text+</span>'+ '</li>' })
ES6则为我们带来了另一种便捷的开发模式,来我们看下字符串模板,模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量,注意需要将变量名写在${}
之中。${}的大括号内部,就是执行JavaScript代码,支持表达式还能调用函数等。
var list = `` res.data.lsit.forEach(function(el,index){ list += ` <li> <img src="${el.src}" /> <span>${el.text}</span> </li> ` })