11.Array
数组¶
数组大小可以变化也可以固定
声明数组
// type arrayName [ arraySize ];
uint balance[10];
// type[] arrayName;
uint balance[];
// 初始化
uint balance[3] = [1, 2, 3];
uint balance[] = [1, 2, 3];
// 赋值
balance[2] = 5;
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract Array {
// 大下可以动态也可以固定
uint256[] public nums = [1, 2, 3];
uint256[3] public numsFixed = [4, 5, 6];
function examples() external {
// 动态数组的增删改查
// 增加
nums.push(4); //[1,2,3,4]
//读取
uint256 x = nums[1]; //2
// 修改
nums[2] = 777; //[1,2,777,4]
// 清空数据
delete nums[1]; //[1,0,777,4]
// 删除数据
nums.pop(); //[1,0,777]
//长度
uint256 len = nums.length; //3
}
}
删除元素
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract ArrayShify {
uint256[] public arr;
function example() public {
arr = [1, 2, 3];
delete arr[1]; //[1,0,3]
}
// 我想直接删掉位置=1的元素怎么办
// 比如我要删除位置=2的,我就从位置=2开始后面的元素左移一位,然后删除最后的
// [1,2,3] --> remove(1) --> [1,3,3] --> [1,3]
// [1,2,3,4,5,6] --> remove(2) --> [1,2,4,5,6,6] -->[1,2,3,4,5]
// [1] --> remove(0) -->[1] -->[0]
function remove(uint256 _index) public {
require(_index < arr.length, "index out of bound");
for (uint256 i = _index; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr.pop();
}
// 另一个简单的
function remove(uint256 _index) public {
arr[_index]=arr[arr.length-1];
arr.pop();
}
}
动态内存数组使用new关键字创建。
uint size = 3; uint balance[] = new uint;
访问数组元素 通过对数组名称进行索引来访问元素。这是通过在数组名称后的方括号中放置元素的索引来完成的。例如: uint salary = balance[2]
;
上述语句将从数组中取出第三个元素并将其赋值给salary变量。以下是一个示例,它将使用上述三个概念,即声明、赋值和访问数组。
- length返回数组的大小。可以使用length来设置动态数组的大小。
- push允许在动态存储数组的末尾追加元素。它返回数组的新长度。