Javascript 子字符串表现奇怪
我创建了一个函数,将 24 小时字符串(又名“0800”或“2330”)转换为分钟。有时字符串会丢失前导零,所以我需要考虑到这一点。
它可以工作,但是为了获得分钟部分,我尝试获取字符串的最后两个字符,人们会假设,这将是这样的:
var timeString = "800"; //Can be "0800"
timeString.substring(timeString.length - 2, 2)
其中,如果您的字符串是“800”(前导零被删除),那么它将相当于
timeString.substring(3 - 2, 2)
但是这不会返回任何东西。如果我使用以下代码,我只会得到“00”(我正在寻找的内容):
timeString.substring(timeString.length, 2)
对我来说,这段代码是错误的,但不知何故它有效?
谁能解释为什么?我是否误解了这个功能的工作原理?
I have created a function to turn a 24 hour string aka "0800" or "2330" into minutes. Sometimes the strings will drop leading zeros so I need to account for this.
It works BUT to get the minute component I try get the last two characters of the string which, one would assume, would be this:
var timeString = "800"; //Can be "0800"
timeString.substring(timeString.length - 2, 2)
Which, if your string is "800" (leading zero dropped) then it would be the equivalent to
timeString.substring(3 - 2, 2)
However this returns nothing what so ever. I only get "00" (what I'm looking for) if I use the following code:
timeString.substring(timeString.length, 2)
To me this code is wrong but it works, somehow?
Can anyone explain why? Have I misunderstood how this function is meant to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
substring 方法中的第二个参数不是您想要的字符数,而是您想要转到的索引。所以现在你将从 substring(3-2, 2)、索引 2 转到索引 2,这不会给你任何字符。
将其更改为:
The second parameter in the substring method isn't the number of characters you want it is the index you want to go to. So right now you are going from substring(3-2, 2), index 2 to index 2, which gives you no characters.
Change it to:
这里第二个参数是 to 字符的索引。
您正在寻找的是 substr 函数。
Here the second parameter is the index of the to character.
What you are looking for is the substr function instead.
所以你要做的就是从索引 2 到 2 获取文本,这显然是一个空字符串。你真的想在这里使用 String.prototype.slice 。它允许您使用负参数作为从末尾开始索引的方式(基本上是字符串长度 - 索引)。不指定第二个参数将提取所有内容,直到字符串末尾。
So what you are doing is, getting the text from index 2 to 2, that's obviously is an empty string. You really want to use String.prototype.slice here. It allows you to use negative parameters as a way to index from the end (basically string-length - index). Specifying no second parameter will extract everything till the end of the string.
您将
substring()
函数与substr()
函数混淆了。substring()
的第二个参数是子字符串的结束索引,而substr()
的第二个参数是字符串的长度。尝试用
substr()
替换substring()
...You've confused the
substring()
function with thesubstr()
function.substring()
's second parameter is the ending index of your substring, whilesubstr()
's second parameter is the length of your string.Try substituting
substr()
forsubstring()
...