es6 模板字符串

模板字符串语法:
	es5写法:
		需要使用大量的“”(双引号)和 + 来拼接才能得到我们需要的模版
		实例:
			"He is " + person.name + " and we wish to know his" + person.age + ".That is all" 
    
	es6写法:
		用`(反引号)标识,用${}将变量括起来
		实例:
			`He is  ${person.name}  and we wish to know his ${person.age} .that is all`
	
注意:
	1. 由于反引号是模版字符串的标识,如果需要在字符串中使用反引号,就需要对其进行转义
		实例:
			`No matter\` what you do , I trust you.` 
	
	2. 模板字符串可以引入变量,不引入变量同样可以使用
		实例:
			`He is  Tom  and we wish to know his 12 .that is all`
			
	3. 可以先定义变量,然后在模版字符串中嵌入变量
		实例:
			let person = {name: 'Tom', age: 12}
			`He is  ${person.name}  and we wish to know his ${person.age} .that is all`
	
	4. 在${}中的大括号里可以放入任意的JavaScript表达式,还可以进行运算,以及引用对象属性。
		实例:
			let x = 10, y = 2;
			`He is  ${person.name}  and we wish to know his ${x + y} .that is all`
	 
	5. 模版字符串还可以调用函数,如果函数的结果不是字符串,那么,将按照一般的规则转化为字符串
		实例:
			function person () { return 'Tom' }
			`He is  ${person()}  and we wish to know his 12 .that is all`
	
	6. 模板字符串中的空格,换行等都会被响应效果
	
	7. 模板字符串中的${}内输入字符串,返回结果仍旧是字符串
		实例:	
			`He is  ${ 'Tom' }  and we wish to know his ${ '12' } .that is all`
			
	8. 模板字符串中还可以嵌套另一个模板字符串

 

你可能感兴趣的:(javascript)