Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

is it necessary to start variable from zero (var i = 0 ) of ' for loop ' ?

javascript

Best Answer BlackRabbit , 08 June 2014 - 08:07 PM

Well, it's not really loop's fault, but arrays indexing.

See, a string is an array of characters, and that arrays starts from position 0 (in many languages, as Java, C#, c++, etc) so, if you want to compare the string from the start you need to cut from 0 and not from 1 (which would be the second character) because that wouldn't match with your string.

In normal conditions, you can pretty much decide how to count, and how to make your loops go, but when it comes to arrays... their first element is zero.

Go to the full post


This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1 B13

B13

    CC Regular

  • Member
  • PipPipPip
  • 28 posts

Posted 08 June 2014 - 07:15 PM

is it necessary to start variable from zero (var  i = 0 ) of ' for loop ' ?  When I used var i =1; then alert massage does not work .But when I put var i =0; then loop started and alert massage worked .
 

var wha = prompt("What is?");
for (var i = 1; i < wha.length; i++) {
if (wha.slice(i,i+12) ==="World War 2" ) {
wha =wha.slice(0,1) + "The Second World War" + wha.slice(i +12);
}
}
alert (wha); 

:confused:


#2 PBJ

PBJ

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 176 posts

Posted 08 June 2014 - 07:46 PM

najmul,

In almost all programming languages, by convention all for loops range from 0 to n -1 (n being the size of some sort of collection or attribute). However, I know that some languages by convention start at 1, therefore I'd suggest looking up the conventions of whatever language that is (Javascript?). If you don't know, generally 0 is a safe bet.



#3 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts

Posted 08 June 2014 - 08:07 PM   Best Answer

Well, it's not really loop's fault, but arrays indexing.

See, a string is an array of characters, and that arrays starts from position 0 (in many languages, as Java, C#, c++, etc) so, if you want to compare the string from the start you need to cut from 0 and not from 1 (which would be the second character) because that wouldn't match with your string.

In normal conditions, you can pretty much decide how to count, and how to make your loops go, but when it comes to arrays... their first element is zero.






Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download