世界互联网乌镇峰会,天津网站优化排名,企业门户账号是什么,网站模板 兼容ie8“路漫漫其修远兮#xff0c;吾将上下而求索。”—— 屈原《离骚》 目录 什么是模板字符串#xff1f;模板字符串特性及代码举例#xff1a;详细举例用法#xff1a; 什么是模板字符串#xff1f;
模板字符串#xff08;Template Literals#xff09;是JavaScript中引入… “路漫漫其修远兮吾将上下而求索。”—— 屈原《离骚》 目录 什么是模板字符串模板字符串特性及代码举例详细举例用法 什么是模板字符串
模板字符串Template Literals是JavaScript中引入的一种新的字符串表示方式它使用反引号而不是单引号或双引号来定义字符串。
模板字符串特性及代码举例
多行字符串模板字符串可以直接包含换行符而不需要使用转义字符\n或字符串连接符来连接多行字符串。
let message Hello,
world!;
console.log(message);
//Hello,
//world!嵌入表达式模板字符串中可以使用${}语法来嵌入表达式。这些表达式会被求值并将其结果转换为字符串后嵌入到模板字符串中。
let name Alice;
let age 30;
let greeting Hello, ${name}! You are ${age} years old.;
console.log(greeting);// Hello, Alice! You are 30 years old.标签模板模板字符串前面可以添加一个“标签”函数该函数可以对模板字符串的内容进行处理并返回一个结果。这提供了一种高级用法允许开发者完全控制模板字符串的处理方式。
let name Alice;
let age 30;
function tag (strings, ...values) {console.log(strings); // 模板字符串中的静态部分console.log(values); // 插值表达式的结果return Tagged template result;
}let result tagMy name is ${name} and I am ${age} years old.;
console.log(result);String.raw方法模板字符串还可以通过String.raw方法来获取“原始”字符串即不对反斜杠\进行转义处理。
let path C:\Users\name;
let rawPath String.rawC:\Users\name;
console.log(path); // 输出: C:\Usersame
console.log(rawPath);// 输出: C:\Users\name详细举例用法
${ }里面可以放表达式、 、-、*、/、普通变量、三目运算符、调用函数等!!!
bodyul/ulstyle.active {color: red;}/stylescriptlet arr [kitty, Alice, Bob];let newList arr.map((item, index) {return li class${index 0 ? active : }b${item}/b/li;})console.log(newList);let oul document.querySelector(ul);oul.innerHTML newList.join()/script
/bodybodyul/ulstyle.active {color: red;}/stylescriptlet name Kitty;let oli lib ${name}/b/lifunction test () {return 自定义添加的内容}let arr [kitty, Alice, Bob];let newList arr.map((item, index) {return li class${index 0 ? active : }b${item}/b${test()}/li;})console.log(newList);let oul document.querySelector(ul);oul.innerHTML newList.join()/script
/body