ES6特性:模板字符串

模板字符串相当于加强版的字符串,用单引号 ` 标识。它可以当作普通普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量或表达式。

// 普通字符串
let str=`hello'\n'world`;  
// hello
// world

// 多行字符串
let str=`hello,
this is a string`;
// hello,
// this is a string

// 字符串中嵌入变量和表达式
let a='x',b='y',c=1;
let str=`hello ${a},world ${b},num is ${c+1}`;    // hello x,world y,num is 2

// 字符串中调用函数
function func(){
    return 'string';
}
let str=`this is ${func()}`;    // this is string

// world没有声明
let str=`hello ${world}`;    //报错

// 字符串原样输出
let str=`hello ${'world'}`;    // hello world   

// 嵌套
const tmp = addrs => `
  <table>
  ${addrs.map(addr => `
    <tr><td>${addr.first}</td></tr>
    <tr><td>${addr.last}</td></tr>
  `).join('')}
  </table>
`;
const data = [
    { first: '<Jane>', last: 'Bond' },
    { first: 'Lars', last: '<Croft>' },
];
tmp(data);
// <table>
//
//   <tr><td><Jane></td></tr>
//   <tr><td>Bond</td></tr>
//
//   <tr><td>Lars</td></tr>
//   <tr><td><Croft></td></tr>
//
// </table>

注:(1)模板字符串中嵌入变量,需要将变量名写在 ${ }

       (2)所有模板字符串的空格和换行,都是被保留的。

       (3)模板字符串的大括号内部,就是执行Javascript代码

       (4)支持嵌套

标签模板,是一个函数的调用,其中调用的参数是模板字符串

alert`hello world`;    等价于    alert('hello world')

当模板字符串中带有变量,会将模板字符串参数处理成多个参数

function func(strArr,...vals){
    let result="";
    for(let i=0;i<strArr.length;i++){
        result+=strArr[i];
        if(vals[i]){
            result+=vals[i];
        }
    }
    return result;
}
let name='xx';
let age=10;
func`my name is ${name},I am ${age+1} years old`; //等价于
func(['my name is ',',I am ',' years old'],'xx',10);
//my name is xx,I am 11 years old

需要注意的是,模板字符串的最开始和最后一定要是普通字符串,如果是变量开始或者结尾,就会出现空字符 " ",这样就能保证第一个参数的长度永远比第二个参数长。

func`my name is ${name},I am ${age}`;    //等价于
func(['my name is ',',I am ',''],'xx',10)

猜你喜欢

转载自blog.csdn.net/qq_41049816/article/details/88245768
今日推荐