1、多行字符串
js里,如果字符串换行,中间需用 + 拼接
var a = 'aaa' +
'bbb' +
'ccc';
ts里,可用 `` 包裹字符串直接换行
var a = `aaa
bbb
ccc`;
2、字符串模板
ts里支持在字符串中插入变量,格式为${},注意字符串必须用``包裹
var name = 'forrest';
var getName = function (){
return 'forrest';
}
console.log(`hello ${name}`);
console.log(`hello ${getName()}`);
有什么用?拼接html时威力就体现出来了
var name = 'forrest';
var getAge = function (){
return 18;
}
console.log(`<div>
<span>name:${name}</span>
<span>age:${getAge()}</span>
</div>`);
省去了一大堆 + 号
3、自动拆分字符串
function test(template, name, age){
console.log(template);
console.log(name);
console.log(age);
}
var name = 'forrest';
var getAge = function (){
return 18;
}
test`hello,my name is ${name},i'm ${getAge()} years old.`
运行结果
使用字符串模板运行test方法,注意格式,注意结果参数