【转载】solidity智能合约[18]-twoarray

solidity

#1

二维数组定义

uint[2][3] grade = [[60,80],[40,20],[50,50]];

返回二维数组

function getGrade() view public returns(uint[2][3]){

    return grade;
}

获取二维数组长度

function getLength() view public returns(uint){

    return grade.length;
}

  function getLength2() view public returns(uint){

    return grade[0].length;
}

改变内容

function changeContent() public {

      grade[0][1] = 100;

     // grade.push(ericGrade);
    //  grade[0][2]=90;
  }

完整代码演示

pragma solidity ^0.4.23;


contract twoArray{
    // uint[2] jonsongrade = [60,80];

     uint[2] ericGrade = [40,20];

    // uint[2] stevenGrade = [50,50];

    uint[2][3] grade = [[60,80],[40,20],[50,50]];


    function getGrade() view public returns(uint[2][3]){

        return grade;
    }

    function getLength() view public returns(uint){

        return grade.length;
    }

      function getLength2() view public returns(uint){

        return grade[0].length;
    }

    //  function changelength()  public {

    //      grade[0].length  =10;
    // }


    function changeContent() public {

        grade[0][1] = 100;

       // grade.push(ericGrade);
      //  grade[0][2]=90;
    }

      //获取内容并求和
    function   add() view public returns(uint){
        uint sum = 0;
              //定义的时候和获取数据的时候有些差别,在获取数据的时候,第一个数字i代表的是i+1元素,第二个数据j代表的是i+1个元素内的第j+1个内容
              //1、   i = 0  i<3
              //2、j=0     j <2
              //3、sum += grade[0][0];、sum += 60;
              //4、j++---->j=1;
              //5.j<2?
              //6.sum+=grade[0][1];sum += 80
              //7.j++------j=2;
              //8.j<2
              //9.i++  --->i=1;
              //10.i<3
              //11.j = 0
              //12.j<2?
              //13.sum += grade[1][0]
              //14.j++
              //15.........
              //最后遍历了grade[0][0],grade[0][1],grade[1][0],grade[1][1],grade[2][0],grade[2][1]
        for(uint i = 0;i<3;i++){
            for(uint j = 0;j<2;j++){
                 sum+= grade[i][j];
            }
        }
        return sum;
    }



}
  • 本文链接: <https ://dreamerjonson.com/2018/11/19/solidity-18-twoarray/>