solidity智能合约[17]-动态长度数组

动态长度数组

动态长度数组可以改变大小和长度

动态长度数组的定义

uint[] grade=[1,2,3,4,5];

返回动态长度数组

1
2
3
function getArray() public view returns(uint[]){
return grade;
}

获取动态数组长度

1
2
3
function getlength() public view returns(uint){
return grade.length;
}

遍历动态长度数组

1
2
3
4
5
6
7
8
9

function cheng() public view returns(uint){

uint result = 1;
for(uint i = 0;i<grade.length;i++){
result *= grade[i]; // result = result * grade[i]
}
return result;
}

改变动态数组长度

1
2
3
4
5
6
7
8
9
10
11
12
//截断
function changeLength() public {
grade.length = 3;
}

function changeLength2() public {
grade.length = 5;
}

function pushelement() public {
grade.push(99);
}