You haven't described enough about your testing methodology for me to know why it appears that the .length
method isn't working. It does.
One possibility is you are expecting a response but the function is state-changing so you will only get a transaction hash. Another possibility is the array isn't populated the way you expect or your inspection functions (not shown) don't work as expected.
The example below has a simple function to populate the student data. It doesn't check for duplicates to keep the example on point. I added an event emitter to make it easier to inspect the iterations, and a getter function so you can inspect the array length directly. Some names have been changed to bring things into alignment with the style guide.
pragma solidity 0.4.25;
contract Loop {
struct StudentStruct {
uint grade;
}
mapping(address => StudentStruct) public studentStructs;
address [] public studentList;
event LogStudentGrade(address student, uint studentGrade);
function appendStudentGrade(address student, uint studentGrade) public {
studentList.push(student);
studentStructs[student].grade = studentGrade;
}
function getStudentCount() public view returns(uint count) {
return studentList.length;
}
function studentLoop() public {
// WARN: This unbounded for loop is an anti-pattern
for (uint i=0; i<studentList.length; i++) {
emit LogStudentGrade(studentList[i], studentStructs[studentList[i]].grade);
}
}
}
The WARN
is about caution with for loops in Solidity. I assume you're just starting out and only wish to see this work as expected. This is a warning for others.
In Remix:
- Deploy the contract
- Add students, score. Repeat multiple times if you want.
- Inspect the count function.
- Sent a transaction to the
studentLoop
- Inspect the transaction Log.
Here it is in Remix to show it working.
Hope it helps.