ES6 模板字符串的认识与扩展

模板字符串

  • 反引号(``),可以保留字符串中的回车、换行。
    支持插入js语句、变量名、表达式、方法的调用等
  const name = "li";
  const str = `hello , ${name}`;
  console.log(str);//hello , li
  • 模板字符串标签函数
    将console.log看作一个打印输出的函数,如下,是一个模板字符串标签函数,它输出的结果是一个数组形式的:[’hello world‘]
const str = console.log(`hello world`); //hello world

如下**myFun()**这种标签函数对模板字符串进行加工,对变量进行处理了,使其返回更合理、更易理解的结果。

 const name = "li";
   const flag = true;
      
   function myFun(Strings,name,gender){
     console.log(Strings,name,flag)//打印出各个参数
     const sex = gender ? "man" : "woman";
     return Strings[0] + name + Strings[1] + sex + Strings[2];
   }
const str = myFun`hello,${name} is a ${flag}`;
console.log(str);//hello,li is a man

这种模板字符串标签函数使文本更加多元化,可以实现很多功能。

ES6 新特性——字符串的扩展
  • includes()
  • starts With()
  • ends With()
const msg = "Hello world!";
console.log(msg.startsWith('Hello'));//true
console.log(msg.endsWith('!'));//true
console.log(msg.includes('o'));//true
  • 参数默认值,在ES6中,不需要再进行a = a === undefined ? true : a;这种判断并赋值默认值,只需要在函数传参中,将默认值放到最后加入传参就行
function fn(str,a = true){
  console.log(a);
}
fn('abc');//true
…操作符用途:
  • 剩余操作符:…加形参名,可以将函数传递的实参,以数组的形式存到变量中,方便之后对变量操作。(注意,存放位置在形参的最后一位且只能出现一次)
function fun(n,...args){
   console.log(args);
}
fun(1,2,3,4,5);//输出:[2,3,4,5]

  • 展开操作符:展开数组
//展开数组一
var arr = [1,2,33,4];
console.log(arr[0],arr[1],arr[2],arr[3]);//0,1,2,33,4
    
//展开数组二
//通过console.log调用apply,使this指向console,再传递实参列表arr,从而展开arr
console.log.apply(console,arr);
    
//展开数组三 ES6 ...方式
console.log(...arr);//1,2,33,4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值