ES6新增的Array方法和String方法、字符串模板
ES6新增了一些字符串方法以及一些数组方法,使数组跟字符串的操作都变得更方便快速。其中字符串新增的方法有includes(),startWith(),endsWith(),repeat()。数组新增的方法有form(),find(),findIndex()。
接下来我们一个个去看它们的用法:
-
includes()
找到返回true,没找到返回false
let str="hello world"; console.log(str.includes('h'));//true console.log(str.includes('a'));//false -
stratWidth()
判断值是否在字符串头部,在的话返回ture,不在的话返回false。
let str="hello world"; console.log(str.startsWith('h'));//true console.log(str.startsWith('e'));//false -
endsWidth()
与startWith()对应,判断值是否在字符串尾部,在的话返回ture,不在的话返回false。
-
repeate()
复制参数次字符串
let str="hello"; console.log(str.repeat(3));//hellohellohello -
字符串模板
它的出现主要是为了便利字符串+变量的情况,往常我们需要对字符串加上双引号然后再加变量名,
如果有多个字符串的情况下代码就会变得很长很繁杂,但字符串模板就简单多了,首先``(esc下那个键)表示字符模板,变量只需加上${变量名}就ok了。还是上代码比较容易看懂。
var name = "javascript" var str = `欢迎来到${name}的世界`; console.log(str);//欢迎来到javascript的世界很简单方便对吧。
接下来看看数组的新增方法:
-
form()
它用来把伪数组变成真数组
var args = { 0: 100, 1: 200, 2: 300, length: 3 }; var arr = Array.from(args); console.log(arr);//[100,200,300]它最常用的场景是这样:假设页面有八个button,通过getElementByTagName得到的是一个伪数组,假设要使用forEach遍历的话就只能先转换成Array才能使用。
var oBtns = document.getElementsByTagName("button"); console.log(oBtns); Array.from(oBtns).forEach(function (el, index) { el.onclick = function () { alert(index); } }) -
find()
它的方法可以这样用:
var arr = [11, 22, 33, 44]; var res = arr.find(function (el, index) { return index == 1; }); console.log(res);//22 -
findIndex()
它跟indexOf的区别在于,findIndex是高阶函数,参数必须是回调函数,但indexOf的参数就是要找的值,找到了就返回该值的下标,没找到就返回-1。相同点在于findIndex在回调函数这样使用也是找到了就返回下标,没找到返回-1。
var arr = [11, 22, 33, 44]; var index = arr.findIndex(function (el) { return el == 22 }); console.log(index);//1

浙公网安备 33010602011771号