Solidity for 循环

1. 语法

Solidity 中, for循环的语法如下:

for (初始化; 测试条件; 迭代语句) {
   // 如果表达式的结果为真,就循环执行以下语句
   ......
}

2. 示例

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SolidityTest {
   uint storedData; 
   
   constructor() {
      storedData = 10;   
   }

   function getResult() public pure returns(string memory){
      uint a = 10; 
      uint b = 2;
      uint result = a + b;
      return integerToString(result); 
   }

   function integerToString(uint _i) internal pure 
      returns (string memory) {
      if (_i == 0) {
         return "0";
      }
      uint j=0;
      uint len;
      for (j = _i; j != 0; j /= 10) {  //for循环的例子
         len++;         
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      while (_i != 0) {
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      return string(bstr);//访问局部变量
   }
}

运行上述程序,输出结果:

0: string: 12

下一章:Solidity break 与 continue

Solidity 循环语句支持 continue 和 break,用来改变循环流程。continue – 跳出本次循环,继续执行下一次循环break – 跳出循环, ...