开发者

what is wrong with this substring?

开发者 https://www.devze.com 2023-02-14 10:15 出处:网络
var mychars = \'abcdefghijklmnopqrstuvwxyz\'; for (i = 0; i < mychars.length; i++) { alert(i开发者_如何转开发.toString() + \" - \" + mychars.substring(i, 1));
var mychars = 'abcdefghijklmnopqrstuvwxyz';
for (i = 0; i < mychars.length; i++) {
  alert(i开发者_如何转开发.toString() + " - " + mychars.substring(i, 1));
}

first of all why does substring(1, 1) not return anything? why does everything after that print more than one character?


The javascript substring method takes two parameters: from and to both indexss. From your code sample it appears you're acting as if it takes (from, length). Try changing your code to the following

alert(i.toString() + " - " + mychars.substring(i, i + 1));


@JaredPar and @Tim Cooper already had explained you what happened. I'd like just to notice that you should use String.substr() method which accept from and length arguments.


It's all in the weird workings of "substring()".

When "i" is 1, then you're asking for all characters from position 1 through position 1 - 1, which is no characters at all.

From the Mozilla docs:

If indexA is larger than indexB, then the effect of substring is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).

Thus for "i" bigger than 1, you get the effect of "substring(1, i)" instead of "substring(i, 1)". Surprise!


Some documentation on the substring function can be found here.

The relevant portion:

This method extracts the characters in a string between "from" and "to", not including "to" itself.


Wow, I just figured it out.

The second parameter is not the count of characters that it's going to get, but the index of the character.

So (0,1) is from nothing to 'a', 1,1 is from 'b' to 'b', meaning empty space, (2,1) goes from 'c' to 'b' and so forth.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号