模板字符串
- 反引号(``),可以保留字符串中的回车、换行。
支持插入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