在 TypeScript 的字符串中插入变量
使用模板文字在 TypeScript 的字符串中插入变量,例如 hello ${myVariable}
。 模板文字用反引号分隔,并允许我们使用美元符号和大括号 ${expression}
语法嵌入变量和表达式。
const str = 'Alfred';
// 👇️ const result: string
const result = `Hello ${str}!`;
// 👇️ "Hello Alfred!"
console.log(result);
我们使用模板文字在字符串中插入变量。
请注意
,字符串包含在反引号 “ 中,而不是单引号中。
TypeScript 能够将模板文字的类型推断为字符串,因为它就是这样——一个允许我们嵌入变量和表达式的字符串。
美元符号和花括号语法允许我们使用被评估的占位符。
const num = 10;
// 👇️ const result: string
const result = `${num + 23} percent`;
console.log(result); // 👉️ "33 percent"
默认情况下,模板文字将各个部分连接成一个字符串。
任何使用美元符号和花括号 ${} 语法传递的表达式都会被评估。
// 👇️ const result: string
const result = `10 multiplied by 5 is ${10 * 5}`;
console.log(result); // 👉️ "10 multiplied by 5 is 50"
我们还可以使用模板文字在多行字符串中插入变量。
const str1 = 'line 1';
const str2 = 'line 2';
const result = `this is ${str1}
this is ${str2}`;
console.log(result);
// 👉️ this is line 1
// 👉️ this is line 2
这非常有用,因为我们不必在每一行都添加换行符,这与连接字符串时相反。
const str1 = 'line 1';
const str2 = 'line 2';
const result = 'this is ' + str1 + '\n' +
'this is ' + str2;
console.log(result);
// 👉️ this is line 1
// 👉️ this is line 2
由于模板文字包含在反引号 “ 中,如果您的字符串包含反引号字符,则必须使用反斜杠对其进行转义。
const str1 = 'hello';
const str2 = 'world';
const result = `${str1}\`${str2}`;
console.log(result); // 👉️ hello`world
我们甚至可以在模板文字中调用函数。
function multiply(a: number, b: number): number {
return a * b;
}
const result = `10 * 5 is equal to ${multiply(10, 5)}`;
console.log(result); // 👉️ "10 * 5 is equal to 50"
当我们在字符串中插入变量时必须合并逻辑时,美元符号花括号语法非常强大。
下面是将三元运算符与模板文字一起使用的示例。
const str1 = 'world';
const str2 = 'one';
// 👇️ const result: string
const result = `${str1.length > str2.length ? str1 : str2}`;
console.log(result); // 👉️ "world"
三元运算符基本上是一个 if/else
语句。 问号之前的部分被评估,如果它返回真,它返回冒号之前的值,否则它返回冒号之后的值。
我们还可以在模板文字中使用逻辑或 ||
和逻辑与 &&
运算符。
const num1 = 0;
const num2 = 50;
// 👇️ const result: string
const result = `${num1 || num2}`;
console.log(result); // 👉️ '50'
逻辑或 ||
运算符如果为真,则返回左侧的值,否则返回右侧的值。
下面是对模板文字使用逻辑与 &&
运算符的示例。
const str1 = 'hello';
const str2 = 'world';
const result = `${str1 && str2}`;
console.log(result); // 👉️ "world"
逻辑与 &&
运算符如果为假,则返回左侧的值,否则返回右侧的值。
这些是在字符串中插入变量或表达式的最常用方法。 使用模板文字时,我们可以合并函数调用和各种逻辑。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。