ES6 模板字符串Template String

1. 模板字符串简介:

  顾名思义,模板字符串是用来定义一个模板是使用的,就像Vue,React中的template语法。

  首先,先来了解一下template string的基本用法: 在ES5中,我们大多都有过拼串的经历吧。

const person = {
    name: 'zhang',
    age: 18,
    hobby: 'coding',
    introduce () {
        console.log('hello, everyone , my name is ' + this.name + ', I am ' + thiss.age + ' years old, I like ' + this.hobby + ' very much.');
    },
}
// 每次敲完这样的代码都有种崩溃的柑橘,万一那个地方不小心删掉了一个引号,然后就...

// 然而在ES6中,为我们提供了模板字符串的功能
const person = {
    name: 'zhang',
    age: 18,
    hibby: 'coding',
    introduce () {
        console.log(`hello, everyone, my name is ${this.name}, I am ${this.age} years old, I like ${this.hobby} very much.`);
    },
}
// 虽然键入的字数没有太太减少,不过至少不用担心会少个引号了

  模板字符串的语法是反引号(`` --> 键盘左上角),利用反引号将字符串封闭起来,模板字符串中可以使用变量,及使用${}的方法,大括号之间可以是JavaScript变量,表达式,也可以是函数执行的结果,这就是模板字符串的基本用法。

const num = 5;
function square (num) {
    return num ** 2;
}

console.log(`the result of square ${num} is ${square(num)}`); 
console.log(`the result of square ${num} is ${num ** 2}`);
// log 'the result of square 5 is 25'

// 需要注意的是。当模板字符串中的变量不是一个字符串时,就会自动调用变量的toString()方法
const person = {
    name: 'zhang',
    age: 18,
    hobby: 'coding',
}
console.log(`hello, ${person}`); // log 'hello, [Object Object]'

person = {
    name: 'zhang',
    age: 18,
    hobby: 'coding',
    toString () {
        return `${this.name} ${this.age}`;
    }
}
console.log(`hello, ${person}`); // log 'hello, zhang 18'
// 会自动调用对象的toString()方法,将对象序列化

2.模板字符串换行

  我们一直都知道JavaScript中普通的字符串是不可以换行的,当我们设计html模板的时候就会出现结构混乱的情况。 

const template = '<ul>
<li></li>
<li></li>
<li></li>
</ul>'   
// ---> 这样的做法在JavaScript中时不被允许的
// 在ES5中,为了使模板的结构更加清晰化,不得不使用拼串的方式实现换行
const template = '<ul>' + 
					'<li></li>' +
					'<li></li>' +
					'<li></li>' +
				'</ul>';
// 可想而知,这样的做法效率挺低的
// 使用模板字符串,里面的字符串就可以换行显示了
const template = `<ul>
					<li></li>
					<li></li>
					<li></li>
				</ul>`
// 使用模板字符串存在一个问题,template string 中的字符串有点类似于<pre></pre>标签中的文本的感觉。模板字符串是会将字符串中的空格都保留下来的,但是在html模板中,
// 渲染到浏览器中时不会将连续的空格渲染到界面上,因此可以正常显示。 // 有了模板字符串,在写Vue,React模板语法的时候也能够方便很多。

   

3.标签模板语法

  在ES6中,模板字符串可以跟在函数名之后,作为参数

alert `123`; // 相当于执行alert('123')

  这种语法相当于是一种特殊的函数调用

let a = 12;
let b = 20;
function fn (strArr, ...rest) {
    console.log(strArr, rest);
}
fn `the sum of ${a} and ${b} is ${a + b}`;

  

  当模板字符串中存在变量时,会将模板字符串分解为多个参数传给标签函数

    1.先将模板字符串中的变量值分离出来,若变量所处的位置在串头或者串尾,则将变量替换为’‘(空串),将

    字符串转换成一个数组作为第一个参数传入函数

    2.将分离出来的变量依次作为变量传给函数

    3.调用函数

    (但是由于变量的参数个数不是固定的,所以通常会用一个rest参数接收变量,并形成数组)

    原本调用的应该是 fn(arrStr, value1, value2, value3);

function concat (arrStr, ...rest) {
    let str = arrStr[0];
    rest.forEach((value, index) => {
        // 在此处可以对字符串做出处理,返回需要的字符串格式
        str += value + arrStr[index + 1];
    })
    console.log(str);
}

// 使用上述函数能够将模板字符串完整地显示出来(虽然好像没有什么太大用处)
let a = 10;
let b = 20;
concat `the sum of ${a} and ${b} is ${a + b}`; // log 'the sum of 10 and 20 is 30'

  2019-03-17 00:32:01

猜你喜欢

转载自www.cnblogs.com/zhangzhengsmiling/p/template_string.html