JS中${}使用

et age = prompt('How old are you?', 100);

alert(`You are ${age} years old!`); // You are 100 years old!

代码第二行中注意使用 ~键下的` `, 而非单引号 ' ' ,才能正确获取变量!

作为新手,在这里容易迷糊。

### JavaScript 模板字符串(Template Literals)的用法 模板字符串是 ES6 引入的一种新特性,允许开发者以更简洁和直观的方式创建多行字符串以及在字符串中嵌入变量或表达式。其基本语法是以反引号(`` ` ``)包裹字符串内容,并使用 `${}` 来插入变量或表达式[^1]。 以下是模板字符串的主要特点和用法: #### 1. 基本语法 模板字符串的基本形式是由反引号包裹的文本。例如: ```javascript const name = "Bill"; const greeting = `Hello ${name}.`; console.log(greeting); // Output: Hello Bill. ``` 上述代码中,`${name}` 是一个占位符,用于插入变量 `name` 的值[^1]。 #### 2. 插入表达式 除了插入变量外,模板字符串还可以插入任意有效的 JavaScript 表达式。表达式将被求值并替换为结果值。例如: ```javascript const a = 5; const b = 10; const message = `The sum of ${a} and ${b} is ${a + b}.`; console.log(message); // Output: The sum of 5 and 10 is 15. ``` #### 3. 多行字符串 模板字符串支持直接书写多行字符串,而无需使用转义字符 `\n` 或者连接符 `+`。例如: ```javascript const multiLine = `This is the first line. And this is the second line.`; console.log(multiLine); // Output: // This is the first line. // And this is the second line. ``` #### 4. 标签模板 模板字符串还支持标签模板功能,允许开发者通过自定义函数处理模板字符串的内容。例如: ```javascript function highlight(strings, ...values) { let result = ''; for (let i = 0; i < values.length; i++) { result += strings[i] + `<strong>${values[i]}</strong>`; } result += strings[strings.length - 1]; return result; } const name = "Alice"; const age = 30; const html = highlight`Name: ${name}, Age: ${age}`; console.log(html); // Output: Name: <strong>Alice</strong>, Age: <strong>30</strong> ``` #### 5. 实际应用示例 模板字符串常用于动态生成 HTML 字符串、日志信息或错误消息等场景。例如: ```javascript const filename = "example.js"; const linenumber = 10; const exception = { message: "SyntaxError", stack: "at example.js:10" }; const errorMessage = `\u2718 Test failure at ${filename}:${linenumber}: ${exception.message} Stack trace: ${exception.stack}`; console.log(errorMessage); // Output: ✘ Test failure at example.js:10: SyntaxError Stack trace: at example.js:10 ``` ### 注意事项 - 模板字符串中的 `${}` 内部可以包含任意合法的 JavaScript 表达式。 - 如果需要在模板字符串中使用反引号,则必须对其进行转义,例如:`\``。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值