es6字符串几个方法的理解

es6字符串

includes(text,index):查找字符字符串是否存在,返回t/f
startsWith(text,index):在指定的index位置查找text是否存在,返回t/f
endsWith(text,index):在指定的index(倒数)位置查找text是否存在,返回t/f
index可写可不写,不写默认是0

"content".includes('con',0);// t
"content".startsWith('con',0);// t 0位索引开始就是con
"content".endsWith('con',0);// f 倒数后面的值查不到

字符串重复复制

repeat(int):返回新的字符串,表示将字符串重复指定次数返回。
int尽量写整数

console.log("=".repeat(5));  // "====="

字符串补齐

padStart(int,text):在文本的左侧补全文本缺失的字符串,text是补缺的文本
padEnd:(int,text):在文本的右侧补全文本缺失的字符串,text是补缺的文本
实现

  "=====error====="  

代码如下:

console.log("error".padstart(10,"="))//=====error,
链式写法
console.log("error".padstart(10,"=").padEnd(15,"="))
//=====error=====,

理解"error".padstart(10,"=")
error为5个长度的字符串,padstart设置的是10位,缺失的字符串=10-5,及缺失5个字符串,所以在error的前面添加5个"=",右侧则相反

使用模板文字创建字符串

const result = {
	  success: ["max-length", "no-amd", "prefer-arrow-functions"],
	  failure: ["no-var", "var-on-top", "linebreak"],
	  skipped: ["no-extra-semi", "no-dup-keys"]
	};

//原生
function makeList(arr) {
  const failureItems = arr.map(item => `<li class="text-warning">${item}</li>`);
  return failureItems;
}
//es6简写

const makeList = arr =>{
	return arr.map(item => `<li class="text-warning">${item}r</li>`)
	}

使用es6箭头函数的时,减少代码了,增加了可读性

posted @ 2021-01-22 16:15  一念天堂tt  阅读(54)  评论(0编辑  收藏  举报