簡體   English   中英

for循環內永無止境

[英]Never ending for within for loop

我正在嘗試將文本轉換為二進制,但是當我的循環運行時,它永遠不會結束。 我不知道為什么會這樣。

有一個更好的方法嗎?

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
      });
    }
}

通過在friendsCopy[i].friendsName += +=中使用+= ,您正在修改friendsCopy[i].friendsName 每次迭代都會變長,因此它永遠不會停止。

如果僅要將其輸出到控制台,請將其更改為

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

您正在通過+=增加friendsName的值
在每個循環迭代中

簡單的解決方案:使用輔助測試參數來存儲起始值:
這樣,測試值在整個循環中都是固定的
例如:

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

您在中斷條件中使用的是friendsName的長度,但是您在循環中不斷增加字符串的長度:

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

請注意,對於循環的每次迭代,不僅要在開始時執行一次friendsCopy[i].friendsName.length

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM