JavaScript 模板文字(模板字符串)

x33g5p2x  于2022-05-05 转载在 Java  
字(2.6k)|赞(0)|评价(0)|浏览(281)

在本教程中,您将借助示例了解 JavaScript 模板文字(模板字符串)。
    模板文字(模板字符串)允许您以字符串的形式使用字符串或嵌入的表达式。它们用反引号括起来``。例如,

const name = 'Jack';
console.log(`Hello ${name}!`); // Hello Jack!

注意:模板文字是在 2015 年引入的(也称为 ECMAScript 6 或 ES6 或 ECMAScript 2015)。一些浏览器可能不支持使用模板文字。访问JavaScript 模板文字支持以了解更多信息。

字符串的模板文字

在早期版本的 JavaScript 中,您可以对字符串使用单引号 ‘’ 或双引号 “”。例如,

const str1 = 'This is a string';

// cannot use the same quotes
const str2 = 'A "quote" inside a string';  // valid code
const str3 = 'A 'quote' inside a string';  // Error

const str4 = "Another 'quote' inside a string"; // valid code
const str5 = "Another "quote" inside a string"; // Error

要在字符串中使用相同的引号,可以使用转义字符 \。

// escape characters using \
const str3 = 'A \'quote\' inside a string';  // valid code
const str5 = "Another \"quote\" inside a string"; // valid code

您可以使用模板文字,而不是使用转义字符。例如,

const str1 = `This is a string`;
const str2 = `This is a string with a 'quote' in it`;
const str3 = `This is a string with a "double quote" in it`;

如您所见,模板文字不仅使包含引号变得容易,而且使我们的代码看起来更干净。

使用模板文字的多行字符串

模板文字也使编写多行字符串变得容易。例如,使用模板文字,您可以替换

// using the + operator
const message1 = 'This is a long message\n' + 
'that spans across multiple lines\n' + 
'in the code.'

console.log(message1)

const message1 = `This is a long message
that spans across multiple lines
in the code.`

console.log(message1)

这两个程序的输出将是相同的。

This is a long message
that spans across multiple lines
in the code.
表达式插值

在 JavaScript ES6 之前,您将使用 + 运算符来连接字符串中的变量和表达式。例如,

const name = 'Jack';
console.log('Hello ' + name); // Hello Jack

使用模板文字,在字符串中包含变量和表达式会更容易一些。为此,我们使用 ${…} 语法。

const name = 'Jack';
console.log(`Hello ${name}`); 

const result = 4 + 5;

// template literals used with expressions
console.log(`The sum of 4 + 5 is ${result}`);

console.log(`${result < 10 ? 'Too low': 'Very high'}`)

输出

Hello Jack
The sum of  4 + 5 is 9
Too low

在模板文字中指定变量和表达式的过程称为插值。

标记模板

通常,您会使用函数来传递参数。例如,

function tagExample(strings) {
    return strings;
}

// passing argument
const result = tagExample('Hello Jack');

console.log(result);

但是,可以使用模板文字创建标记模板(其行为类似于函数)。您使用的标记允许您使用函数解析模板文本。
    标记模板的编写方式与函数定义类似。但是,在调用文本时不传递括号()。例如,

function tagExample(strings) {
    return strings;
}

// creating tagged template
const result = tagExample`Hello Jack`;

console.log(result);

输出

["Hello Jack"]

字符串值数组作为标记函数的第一个参数传递。还可以将值和表达式作为剩余参数传递。例如,

const name = 'Jack';
const greet = true;

function tagExample(strings, nameValue) {
    let str0 = strings[0]; // Hello
    let str1 = strings[1]; // , How are you?

    if(greet) {
        return `${str0}${nameValue}${str1}`;
    }
}

// creating tagged literal
// passing argument name
const result = tagExample`Hello ${name}, How are you?`;

console.log(result);

输出

Hello Jack, How are you?

这样,您还可以在标记的模板中传递多个参数。

上一教程 :JS Default Parameters                                          下一教程 :JS Spread Operators Class

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/template-literal

相关文章

微信公众号

最新文章

更多