1. 程式人生 > >solidity智慧合約[17]-動態長度陣列

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

image.png