JavaScript exhibits zero based indexing , that is, the first element in an array or in a string is at position 0
.(JavaScript展示了从零开始的索引 ,即数组或字符串中的第一个元素在位置0
。)
Therefore, an array or string of length n
has elements going from position 0
to n - 1
, with element at position n
being undefined
.(因此,长度为n
的数组或字符串具有从位置0
到n - 1
元素,位置n
元素是undefined
。) This means that an array or string with n
elements has the last element at n - 1
, which is accessed as someArrayString[n - 1]
.(这意味着具有n
元素的数组或字符串的最后一个元素位于n - 1
,可以通过someArrayString[n - 1]
。)
.length
returns the length of an array or a string.(.length
返回数组或字符串的长度。)
Hence, the last element of an array or a string is found at someArrayString.length - 1
which is accessed as someArrayString[someArrayString.length - 1]
.(因此,数组或字符串的最后一个元素位于someArrayString.length - 1
,可以通过someArrayString[someArrayString.length - 1]
。)
From the code, it can be inferred that word
is a string
.(从代码中可以推断出word
是一个string
。)
Therefore, the line word[word.length-1]
accesses the last char (letter) in the word
(although it actually accesses the last code unit but in ASCII a code unit correspond with a 1 byte ASCII char).(因此,线word[word.length-1]
访问在最后一个字符(字母) word
(虽然它实际上访问的最后代码单元 ,但在ASCII用1个字节的ASCII字符码单元对应)。)
For example, the string var word = "JavaScript"
has length 10
.(例如,字符串var word = "JavaScript"
长度为10
。)
With J
at position 0
and t
at position 9
.(J
在0
位置, t
在9
位置。) In other words, word[0] == 'J'
and word[word.length - 1] == 't'
(换句话说, word[0] == 'J'
和word[word.length - 1] == 't'
) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…