Strings
JavaScript Lesson 4 2:32 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A string is text in quotes, and a plus between two strings joins them — concatenation, if you want the proper word.
字符串就是引号里的文字,两个字符串之间的加号会把它们连起来—— 正式的说法叫拼接。
Here the greeting is built from three pieces: a piece of text, the variable, and another piece of text.
这里的问候语由三部分拼成:一段文字、那个变量、再一段文字。
Look closely at the first one.
仔细看第一部分。
The space after the comma is inside the quotes, because plus adds nothing of its own — leave the space out and you get Hello comma Sam with no gap.
逗号后面的空格在引号里面, 因为加号自己不会添任何东西——不写这个空格,你得到的就是没有间隔的 Hello,Sam。
Three things you will reach for constantly.
有三样东西你会经常用到。
Dot length counts the characters in a string — hello is five.
.length 数出字符串里有多少个字符——hello 是 5。
Dot toUpperCase gives you a copy in capitals, and dot toLowerCase a copy in small letters.
.toUpperCase() 给你一个全大写的副本,.toLowerCase() 给你一个全小写的副本。
One detail worth memorising now: length takes no brackets, because it is a property rather than a job, while the other two do.
有个细节现在就该记住:length 后面不加括号,因为它是一个属性而不是一件要做的事, 而另外两个要加括号。
And both of those return a NEW string — the original is untouched, so store the result if you want it.
这两个方法都返回一个新的字符串—— 原来的字符串没有变,所以想留住结果就要把它存起来。
Every character sits at a numbered position, and the numbering starts at zero.
每个字符都待在一个编号的位置上,而编号从 0 开始。
So the J of JAVASCRIPT is at position zero, and the fourth character is at position three — that off-by-one is worth saying out loud until it sticks.
所以 JAVASCRIPT 的 J 在位置 0,第四个字符在位置 3—— 这个差一的地方值得多念几遍,直到记牢。
To take a longer piece, use slice with a start and an end: zero to four runs up to four without including it, giving J, A, V, A.
要取更长的一段,就用 slice,给它一个起点和一个终点: 0 到 4 会一直取到 4,但不包含 4,得到 J、A、V、A。
Same rule as the index: count from zero, stop before the end.
规则和索引一样:从 0 开始数,在终点之前停下。
Now the lesson's first task: greet somebody by name.
现在做课程里的第一道题:按名字问候某个人。
Store the name, then log three pieces joined in order — Hello comma space, the name, an exclamation mark.
先把名字存起来,然后按顺序把三部分拼起来打印—— "Hello, "、名字、还有一个感叹号。
Run it and the console shows Hello, Sam, exactly as written.
运行它,控制台显示 Hello, Sam!,和写的一模一样。
If yours comes out looking cramped, the space is what is missing, and it belongs inside the quotes, not beside the plus.
如果你的输出看起来挤在一起,那缺的就是那个空格, 而它属于引号里面,不是放在加号旁边。
Four things to take with you.
带走四点。
One: plus joins strings, and any space you want must be inside the quotes.
第一:加号拼接字符串,你想要的空格必须写在引号里面。
Two: length counts characters and takes no brackets.
第二:length 数字符个数,而且不加括号。
Three: positions start at zero, so the fourth character is word, square brackets, three.
第三:位置从 0 开始,所以第四个字符是 word 。
Four: slice stops before its second number.
第四:slice 在第二个数字之前停下。
Now do the four tasks; the last one is a single character by position.
现在去做那四道题;最后一题是按位置取一个字符。