// 获取所有分类对象
function getAllCategory() public view returns (Category[] memory) {
string[] memory _categoryNames = this.getAllCategoryName();
uint len = _categoryNames.length;
Category[] memory _categorys;
for (uint i = 0; i < len; i++) {
_categorys[i] = nameToCategory[_categoryNames[i]];
}
return _categorys;
}
此时函数会报错:
revert
The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.
是因为变长数组使用前必须确定数组长度。添加一行代码之后如下:
// 获取所有分类对象
function getAllCategory() public view returns (Category[] memory) {
string[] memory _categoryNames = this.getAllCategoryName();
uint len = _categoryNames.length;
Category[] memory _categorys;
//变长memory数组,使用前必须确定长度
_categorys = new Category[](len);
for (uint i = 0; i < len; i++) {
_categorys[i] = nameToCategory[_categoryNames[i]];
}
return _categorys;
}
可以正常运行。
解决问题的文章链接: