solidity智能合约[18]-twoarray

二维数组定义

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

返回二维数组

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

return grade;
}

获取二维数组长度

1
2
3
4
5
6
7
8
9
function getLength() view public returns(uint){

return grade.length;
}

function getLength2() view public returns(uint){

return grade[0].length;
}

改变内容

1
2
3
4
5
6
7
function changeContent() public {

grade[0][1] = 100;

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

完整代码演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

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



}