简体   繁体   English

for循环内永无止境

[英]Never ending for within for loop

I'm trying to convert text to binary but when my loop runs, it never ends. 我正在尝试将文本转换为二进制,但是当我的循环运行时,它永远不会结束。 I cannot figure out why that is so. 我不知道为什么会这样。

Is there a better way to do this? 有一个更好的方法吗?

handleBinaryChange: function(e){
    var friendsCopy = this.state.friendsArray;
    for (var i = 0; i < friendsCopy.length; i++) {
        for (var j = 0; j < friendsCopy[i].friendsName.length; j++) {   
          console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
        }//End of 'j' for
      }//End of 'i' for

      this.setState({
          friendsArray: friendsCopy //make friendsCopy contain the new value for friendsName
      });
    }
}

By using += in friendsCopy[i].friendsName += you are modifying friendsCopy[i].friendsName . 通过在friendsCopy[i].friendsName += +=中使用+= ,您正在修改friendsCopy[i].friendsName On each iteration it gets longer, so it never stops. 每次迭代都会变长,因此它永远不会停止。

If you only want to output it to the console change it to 如果仅要将其输出到控制台,请将其更改为

friendsCopy[i].friendsName + friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");

You are increasing friendsName value with += 您正在通过+=增加friendsName的值
in each loop iteration 在每个循环迭代中

simple solution: use an auxiliary test parameter that stores the starting value: 简单的解决方案:使用辅助测试参数来存储起始值:
this way, test value is fixed throughout the entire loop 这样,测试值在整个循环中都是固定的
eg: 例如:

for(var i=0; i<friendsCopy.length; i++){

  var test = friendsCopy[i].friendsName.length; // added this param
  for(var j=0; j<test; j++){   // used it here

    console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");

  }//End of 'j' for

}//End of 'i' for

You are using the length of friendsName in your break condition, but you keep increasing the length of the string inside the loop: 您在中断条件中使用的是friendsName的长度,但是您在循环中不断增加字符串的长度:

for(var j=0; j<friendsCopy[i].friendsName.length; j++){   
    console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}

Note that friendsCopy[i].friendsName.length will be executed for each iteration of the loop, not only once at the beginning. 请注意,对于循环的每次迭代,不仅要在开始时执行一次friendsCopy[i].friendsName.length

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

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