Skip to content

Template literals

JavaScript Lesson 5 2:22 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
You already know how to build a sentence out of pieces: joining with pluses. 你已经知道怎么用一段段拼出一句话:用加号连接。
It works, and it gets ugly fast — four fragments, two pluses, quotes opening and closing, and a space that is easy to lose. 这样能用,但很快就会变得难看——四个片段、两个加号、引号开开合合, 还有一个很容易丢掉的空格。
There is a neater way. 有一种更整洁的写法。
Wrap the whole thing in backticks instead of quotes, and write the values where they belong. 把整句话用反引号包起来,而不是引号,然后把值直接写在它该在的位置。
Both lines print the same sentence; only one of them looks like it. 两行打印出的是同一句话;但只有一行看起来像那句话。
Here is what actually happens. 来看实际发生了什么。
Inside backticks, a dollar sign with curly brackets marks a hole in the text. 在反引号里面,一个美元符号加花括号标出文字中的一个空位。
When the line runs, JavaScript looks at what is written in the hole, finds its value, and its value goes in — right where the hole was, with the text either side untouched. 这一行执行时,JavaScript 会看空位里写的是什么,求出它的值, 然后把值放进去——就放在空位原来的地方,两边的文字丝毫不动。
What comes out is one finished string, exactly as if you had typed it by hand. 出来的结果是一个完整的字符串,就跟你手打出来的一模一样。
A hole does not have to hold a variable. 空位里不一定要放变量。
Put a sum inside and it is worked out first, so a plus b equals, then the answer, all in one line of text. 放一个算式进去,它会先被算出来, 于是 a、加号、b、等号,再加上答案,全在一行文字里。
Put a multiplication inside and you get Total: ten without a separate calculation. 放一个乘法进去,你直接得到 Total: 10,不用另外算一次。
You can even call a method in there. 你甚至可以在里面调用一个方法。
The rule is simple: inside the braces you are writing JavaScript, not text. 规则很简单:花括号里面你写的是 JavaScript,不是文字。
One thing goes wrong more than anything else here, and it produces no error at all. 这里出错最多的是同一件事,而且它完全不会报错。
Use an ordinary quote and the dollar-brace is just more text, so the console prints the placeholder itself, brackets and all. 用普通引号,${ } 就只是普通文字,于是控制台把这个占位符原样打印出来, 连括号一起。
With a backtick, the value goes in. 用反引号,值才会被放进去。
If you ever see dollar-brace in your output, that is the whole diagnosis. 如果你在输出里看到 ${…},诊断到此结束,就是这个原因。
The backtick is the key above Tab, left of the number one. 反引号在 Tab 键上面那一排,数字 1 的左边。
Four things to take with you. 带走四点。
One: backticks make a template literal. 第一:反引号构成模板字符串。
Two: dollar-brace marks a hole, and the value is dropped in where it stands. 第二:${ } 标出一个空位,值会被放进它所在的位置。
Three: anything with a value fits inside the braces — a variable, a sum, a method call. 第三:任何有值的东西都能放进花括号——变量、算式、方法调用。
Four: a plain quote prints the placeholder itself, which is your clue that the backtick is missing. 第四:普通引号会把占位符原样打印出来,这就是你少写了反引号的线索。
Now do the three tasks; all three want a template literal. 现在去做那三道题;三题都要用模板字符串。

Log in or create account

IGCSE, A-Level & AP