Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - 了解.length属性(Understanding the .length property)

Could someone please explain what the .length property is doing in the following code:(有人可以在下面的代码中解释.length属性的作用:)

let sentenceCount = 0;
betterWords.forEach(word => {
  if (word[word.length-1] === '.' || word[word.length-1] === '!') {
    sentenceCount++;
  }
});

I understand the basic idea of what .length does, but when I try to print out word[word.length] , it prints out as undefined .(我了解.length的基本概念,但是当我尝试打印出word[word.length] ,它会打印为undefined 。)

If I print out word[word.length-1] , then I get the .(如果我打印出word[word.length-1] ,则得到.) and !(和!) in the text.(在文本中。) I'm not understanding what word[word.length-1] actually is so that when -1 is attached it gets the characters on the end.(我不了解word[word.length-1]实际上是什么,因此当附加-1时,它的末尾会出现字符。)

Thank you in advance for any advice on this.(预先感谢您的任何建议。)

  ask by bpTheCoder translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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的数组或字符串具有从位置0n - 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 .(J0位置, t9位置。) In other words, word[0] == 'J' and word[word.length - 1] == 't'(换句话说, word[0] == 'J'word[word.length - 1] == 't')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...