0

In my project, I want to count the elements of an array as follows:

    struct Server{
    
       uint sernum;
       uint num;
       uint data;
    }
    Server [] public datta;


    
    function count() public constant returns(uint sercount) {
        
        return datta.length;
    }
    function set_data (uint Sernum ,uint Num, uint Data  ) public  {
        Server memory xserver = Server(Sernum,Num,Data);
        uint x= count();
        bool y;
        if(x>=1){
            
            for (uint i = 0; i<datta.length;i++){
            
                if(datta[i].sernum == Sernum && datta[i].num==Num && datta[i].data<Data){
                    
                    y=true;
                }
                else{
                    
                    y==false;
                }
            }
            if (y==true){
              
                datta.push(xserver);
      }
   }

When I call a count function to see how many elements in the array it always gives me 1 no matter how many of the elements of the array

   print( format(contract.functions.count().call()))

How do I count the elements of an array ??

1
  • The good way is datta.length. You may have an issue in your algorithm. Commented Aug 31, 2020 at 7:12

2 Answers 2

0

check your test script, there is some problem with parentheses. By the way, I tried to imagine the sense of the script. I guess you call the function set_data(...) as many times as the elements you want to add, but for example if the input is always the same, in particular the Data parameter, then the element will be added only the first time because the Y boolean only in that case is TRUE, because of the line "datta[i].data<Data".

0

If you are using web3.js, you can use let length = await contract.methods.count().call() to get the count the array.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.