本文介绍了在 Solidity 中使用嵌套数组的基本概念和操作,包括如何定义、访问和处理嵌套数组,并提供了相关代码示例。
在实际应用中,嵌套数组很少被使用,但为了保持完整性,我们将其包含在此。
嵌套数组,顾名思义,指的是包含在另一个数组中的数组。
在这个例子中,该函数接收一个矩形的网格。
contract ExampleContract {
function containsAThree(uint256[][] calldata nestedArray)
public
pure
returns (bool) {
for (uint256 i = 0; i < nestedArray.length; i++) {
for (uint256 j = 0; j < nestedArray[i].length; j++) {
if (nestedArray[i][j] == 3) {
return true;
}
}
}
return false;
}
}
这是在 remix 中运行的情况。
你也可以从二维数组中获取一维数组。
contract ExampleContract {
// [[1,2],[3,4],[5,6]] 变成 [1,2]
function getRow(uint256[][] calldata nestedArray)
public
pure
returns(uint256[] memory) {
return nestedArray[0];
}
}
要声明固定大小的数组,请使用以下语法。
contract ExampleContract {
// ACCEPTED: [[1,2],[3,4],[5,6]]
// REJECTED: [[1,2,3],[4,5,6]]
function fixedSize(uint256[2][3] calldata nestedArray)
public
pure
returns (uint256) {
return 0; // 仅仅为了编译
}
}
可能让人困惑的是,当你访问数组中的特定元素时,顺序可能感觉与其他语言相反,但如果你仔细想想,这是有道理的。
contract ExampleContract {
// ACCEPTED: [[1,2],[3,4],[5,6]] -> 返回 6
function getLast(uint256[2][3] calldata nestedArray)
public
pure
returns (uint256) {
return nestedArray[2][1];
// nestedArray[2] -> [5,6] 然后获取第 1 个索引项 -> 6
}
}
就像一维数组一样,如果你访问越界的区域,交易将会回退。
请注意,嵌套数组在实际应用中非常罕见。如果你觉得可以跳过这一部分,请随意。
练习题
请查看 区块链培训营,以了解更多关于智能合约开发和代币标准的内容。
- 原文链接: rareskills.io/learn-soli...
- 登链社区 AI 助手,为大家转译优秀英文文章,如有翻译不通的地方,还请包涵~
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!