简体   繁体   中英

Why does the modulo operator appear to work differently in FOR loops in javscript?

I'm making a simple javascript function that takes an input of a string and pads it to the nearest multiple of 8. The function works, however it appears that the modulo operator works differently in for loops. For example:

var text = "abcdefghi"
if(text.length % 8 !== 0){
  var amt = 8 - (text.length % 8)
  for (let i = 0; i < amt; i++) {
    text = text + "#"
  } 
}
console.log(text)

Returns: abcdefghi#######

But:

var text = "abcdefghi"
if(text.length % 8 !== 0){
  for (let i = 0; i < text.length % 8; i++) {
    text = text + "#"
  }
}
console.log(text)

Also Returns: abcdefghi#######

From my understanding of the modulo operator text.length % 8 = 1 given a string input of 9 characters. So therefore in order to pad the string to make it 16 characters I would have to do 8 - (text.length % 8) = 7 . When I put that into it's own variable so that amt = 7 the for loop loops 7 times and works correctly. However, when I do the operation in the for loop and remove 8 - it also loops 7 times even though text.length % 8 = 1 . Can someone explain what's going on here?

The for loop will evaluate the length of the text every time it runs through the loop. So if you add a hashtag onto the end of the text in the loop, when it evaluates the length again, it will see that the text is one longer than it was last time.

So basically you are adding the text than finding the length again, when you get the length of text outside the for loop, you will get a constant of the length and be able to accurately use it in the for loop.

To put it to an example, when you do the constant length, like what you did in your first example outside of the for loop, you have an equation like:

repeat until x = y

But if you do the calculation inside the for loop, you get an equation like:

repeat until x = x + 1

That just doesn't work because x is not going to equal itself + 1 if you recalculate what x + 1 is every time you increment x.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM