简体   繁体   English

为什么模运算符在 javscript 的 FOR 循环中的工作方式不同?

[英]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.我正在制作一个简单的 javascript 函数,它接受一个字符串的输入并将其填充到最接近的 8 的倍数。该函数可以工作,但是似乎模运算符在 for 循环中的工作方式有所不同。 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#######返回: 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#######还返回: abcdefghi#######

From my understanding of the modulo operator text.length % 8 = 1 given a string input of 9 characters.根据我对模运算符text.length % 8 = 1理解,给定 9 个字符的字符串输入。 So therefore in order to pad the string to make it 16 characters I would have to do 8 - (text.length % 8) = 7 .因此,为了填充字符串以使其成为 16 个字符,我必须执行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.当我将它放入它自己的变量中时, amt = 7 for 循环循环 7 次并正常工作。 However, when I do the operation in the for loop and remove 8 - it also loops 7 times even though text.length % 8 = 1 .但是,当我在 for 循环中执行操作并删除8 -即使text.length % 8 = 1它也会循环 7 次。 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. for 循环将在每次运行循环时评估文本的长度。 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.所以基本上你是在添加文本而不是再次找到长度,当你在 for 循环之外得到文本的长度时,你将得到一个长度常量,并且能够在 for 循环中准确地使用它。

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:举个例子,当你做恒定长度时,就像你在 for 循环之外的第一个例子中所做的那样,你有一个等式:

repeat until x = y

But if you do the calculation inside the for loop, you get an equation like:但是如果你在 for 循环中进行计算,你会得到一个等式:

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.这是行不通的,因为如果每次增加 x 时都重新计算 x + 1 是什么,x 不会等于自身 + 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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