ES6扩展
程序员文章站
2022-06-23 22:32:00
模板字符串和标签模板 const getCourseList = function() { // ajax return { status: true, msg: '获取成功', data: [{ id: 1, title: 'Vue 入门', date: 'xxxx-01-09' }, { id: ......
模板字符串和标签模板
const getcourselist = function() { // ajax return { status: true, msg: '获取成功', data: [{ id: 1, title: 'vue 入门', date: 'xxxx-01-09' }, { id: 2, title: 'es6 入门', date: 'xxxx-01-10' }, { id: 3, title: 'react入门', date: 'xxxx-01-11' }] } }; const { data: listdata, status, msg } = getcourselist(); function foo(val) { return val.replace('xxxx', '2020'); } if (status) { let arr = []; listdata.foreach(function({ date, title }) { arr.push( ` <li> <span>${ `课程名: ${ title }` }</span> <span>${ foo(date) }</span> </li> ` ); }); let ul = document.createelement('ul'); ul.innerhtml = arr.join(''); document.body.appendchild(ul); } else { alert(msg); }
padstart padend
{ let str = 'i'; // 插入在5的位置 let str1 = str.padstart(5, 'mooc'); console.log(str1); // 倒序插入在5的位置 let str2 = str.padend(5, 'mooc'); console.log(str2); }
repeat
{ function repeat(str, num) { return new array(num + 1).join(str); } console.log(repeat('s', 3)); }
startswith endswith
{ const str = 'a promise is a promsie'; console.log(str.startswith('b')); console.log(str.startswith('a pro')); console.log(str.endswith('promsie')); console.log(str.endswith('a')); }
includes
{ const str = 'a promise is a promise'; if (~str.indexof('promise')) { console.log('存在"promise"'); } if (str.includes('a promise')) { console.log('存在"a promise"'); } }
字符串转数组+遍历
let str = 'promise'; // 四种方法:转成数组后遍历 var ostr = array.prototype.slice.call(str); var ostr = str.split(''); const ostr = [...str]; const [...ostr] = str; console.log(ostr); //单个字符输出 ostr.foreach(function(word) { console.log(word); });
对全是英文的字符串中的大写字符加密 a -> 100 b -> 99
const map = {a: '100', b: '99', c: '98', d: '97', e: '96', f: '95', g: '94', h: '93', i: '92', j: '91', k: '90', l: '89', m: '88', n: '87', o: '86', p: '85', q: '84', r: '83', s: '82', t: '81', u: '80', v: '79',w: '78',x: '77',y: '76', z: '75'}; const words = 'abcdefghijklmnopqrstuvwxyz'; ostr.foreach(function(word, index) { if (words.includes(word)) ostr[index] = map[word]; }); console.log(ostr.join(''));
使用for-of遍历字符串
let str = 'promise'; let newstr = ''; const map = {a: '100', b: '99', c: '98', d: '97', e: '96', f: '95', g: '94', h: '93', i: '92', j: '91', k: '90', l: '89', m: '88', n: '87', o: '86', p: '85', q: '84', r: '83', s: '82', t: '81', u: '80', v: '79',w: '78',x: '77',y: '76', z: '75'}; for (let word of str) { if (str.includes(word)) newstr += map[word]; } console.log(newstr);
unicode是一项标准,包括字符集、编码方案等
解决传统的字符编码方案的局限
上一篇: ts中接口的用法