深入浅出es6模板字符串

深入浅出es6模板字符串

本文主要介绍了深入浅出es6模板字符串,分享给大家,具体如下

作为前端开发者避免不了根据后台数据的返回,组装html,渲染页面。举个栗子

$('#result').append( 'There are <b>' + basket.count + '</b> ' + 'items in your basket, ' + '<em>' + basket.onSale + '</em> are on sale!');

有时候还要给标签加一些属性,写起来很不方便,es6提供了模板字符串的方法,简化了这一过程

$('#result').append(` There are <b>${basket.count}</b> items  in your basket, <em>${basket.onSale}</em> are on sale!`);

所有模板字符串的空格和换行,都是被保留的,如果你不想要前后换行,可以使用trim方法消除它。

在{}你可以写任意JavaScript表达式,包括调用函数

var x = 1;var y = 2;`${x} + ${y} = ${x + y}`// "1 + 2 = 3"`${x} + ${y * 2} = ${x + y * 2}`// "1 + 4 = 5"var obj = {x: 1, y: 2};`${obj.x + obj.y}`// "3"function fn() { return "Hello World";}`foo ${fn()} bar`// foo Hello World bar

如果变量没有声明,会报错,如果{}中是一个字符串,则原样返回

// 变量place没有声明var msg = `Hello, ${place}`;// 报错`Hello ${'World'}`// "Hello World"

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

tag:字符串模板深入浅出电脑软件

相关内容