es6模板字符串用反引号包裹,支持${}变量插值、多行文本、嵌套表达式;可嵌入三元运算、函数调用、逻辑运算及动态生成html或url等复杂结构。

ES6 模板字符串通过反引号(`)包裹,配合 ${} 语法实现变量插值,天然支持多行和嵌套表达式,拼接复杂变量非常直观。
基础变量与表达式拼接
直接在 ${} 中写变量名、属性访问、函数调用或简单运算,JS 会自动求值并转为字符串:
const name = "Alice"; const age = 28; console.log(`Hello ${name}, you are ${age + 1} next year.`);const user = { id: 101, profile: { city: "Beijing" } }; console.log(`User ${user.id} lives in ${user.profile.city}.`);console.log(`Result: ${Math.max(3, 7, 5)}`); // "Result: 7"
条件逻辑与三元运算嵌入
模板字符串内部可直接使用三元运算符或逻辑表达式,避免提前拼接或冗余变量:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
const score = 85; console.log(`Grade: ${score >= 90 ? "A" : score >= 80 ? "B" : "C"}`);const items = ["apple", "banana"]; console.log(`You have ${items.length} item${items.length !== 1 ? "s" : ""}.`);const user = { name: "Bob", email: null }; console.log(`Contact: ${user.email || "Not provided"}.`);
调用函数或复用逻辑块
把格式化逻辑封装成函数,在插值中直接调用,提升可读性和复用性:
const formatDate = d => new Date(d).toLocaleDateString("zh-CN"); console.log(`Created on ${formatDate("2023-05-20")}.`);-
const highlight = text => `<strong>${text}</strong>`; console.log(`Message: ${highlight("Important!")}`);(注意:仅用于展示,实际渲染需防 XSS) const getFullName = u => [u.first, u.middle, u.last].filter(Boolean).join(" "); const person = { first: "John", last: "Doe" }; console.log(`Full name: ${getFullName(person)}`);
嵌套模板字符串与动态生成
模板字符串本身可作为值参与更复杂的拼接,适合生成 HTML 片段或配置文本:
const rows = [{id: 1, name: "A"}, {id: 2, name: "B"}]; const html = `<table>${rows.map(r => `<tr> <td>${r.id}</td> <td>${r.name}</td> </tr>`).join("")}</table>`;const prefix = "DEBUG"; const msg = "timeout"; console.log(`${prefix}: ${msg.toUpperCase()} occurred.`);const config = { host: "api.example.com", port: 443 }; const url = `https://${config.host}:${config.port}/v1/data`; console.log(url);
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










