ES6中的模板字面量是什么

ES6中的模板字面量是什么

模板字面量 是在ECMAScript6中引入的新特性,它提供了一种简单的方法来进行字符串插值和多行字符串创建。

在ES6(ECMAScript 6)引入之前,模板字面量被称为模板字符串。从ES6开始,我们有了以 反引号 (`) 字符表示的模板字面量。模板字面量还可以用于保存占位符,占位符由 ‘$’ 符号和 {} 大括号表示,例如 (${expression}).

语法:

`Any string ${jsExpression} can appear here`
JavaScript

示例: 在这个示例中,我们将演示模板字面量的简单示例。

Javascript

const str1 = `Hi, GeeksforGeeks Learner`;
console.log(str1);
 
const str = "GeeksforGeeks";
const str2 = `Hi, ${str} Learner`;
console.log(str2);
JavaScript

结果:

Hi, GeeksforGeeks Learner
Hi, GeeksforGeeks Learner
JavaScript

优点:

使用模板字符串具有以下优点:

1. 字符串连接:

模板字面量提供了一种更简单的方法来连接两个字符串。通常使用 “+”运算符 ,但使用模板字符串,我们可以编写任何我们想要的内容。

示例:

Javascript

const strA1 = "Normal Javascript techniques";
const strA2 =  "are a little bit lengthy";
console.log(strA1 + " " + strA2 + ".");
 
const strB1 = "Template literals";
const strB2 =  "make them simple";
console.log(`{strB1}{strB2}.`);
JavaScript

输出:

Normal Javascript techniques are a little bit lengthy.
Template literals make them simple.
JavaScript

2. 无需使用\n和\t转义字符: 模板字面量可以保留每种类型的空格,因此我们无需明确指定换行或额外的空格。

示例:

Javascript

console.log("There will be a tab space after this"
    + "\t" + "end of string.");
console.log("First Line" + "\n" + "Second Line");
 
console.log(`There will be a tab space    after this end of string.`);
console.log(`First Line 
Second Line`);
JavaScript

输出:

There will be a tab space after this    end of string.
First Line
Second Line
There will be a tab space after this    end of string.
First Line
Second Line
JavaScript

3. 表达式和字符串的组合变得容易: 使用模板字面量,我们可以将任何类型的表达式嵌入到字符串中,在运行时进行执行和确定。

示例 1: 在这个示例中,我们展示了如何使用三元运算符来生成一个带有模板字面量的动态字符串。

Javascript

let darkMode = true;
 
console.log(
    `The current background color
    is ${darkMode ? "#000000" : "#FFFFFF" }`
);
JavaScript

输出:

The current background color
is #000000
JavaScript

示例2: 数学表达式如何插入模板字面量的简单示例。

JavaScript

const price = 5799.00;
 
console.log(
    `The price of product is {price} and
    after 16% discount it would cost{price-price*16*0.01}`
);
JavaScript

输出结果:

The price of product is 5799 and
after 16% discount it would cost 4871.16
JavaScript

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册