Skip to main content

数组

  • 数组分为动态数组和固定长度的数组
  • 数组初始化
  • 数组操作(push,get,update,delete,pop,length)
    • delete: 操作不会改变数组长度,只是将对应位置的值设为默认值
    • push: 在数组尾部追加一个元素
    • pop: 弹出数组最后一个元素
    • push 和 pop 不能用于固定长度数组,因为会改变数组长度
  • 在内存中创建数组
    • 内存中不能创建动态数组,只能创建固定长度的数组
    • 内存中创建的数组不能使用 push、pop 方法,因为会改变数组长度
  • 在函数中返回数组所有内容
    • 定义数组为 public,外部访问时需要输入数组下标才能获取对应下标的值,不能获取所有数组内容

示例

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;

contract Array {
uint[] public nums;
uint[3] public numsFixed;
uint[] public initNums = [1,2,3];
uint[3] public initFixedNums = [4,5,6];

function arrayOptions() external {
// 数组最后追加一个元素
initNums.push(4); // 【1,2,3,4】
// 弹出数组最后一个元素
initNums.pop();
// 获取数组对应下标的元素
uint x = initNums[1]; // 2
// 修改对应下标的值
nums[2] = 777; // [1,777,3]
// 将数组对应下标的值设为默认值
delete initNums[1];
// 获取数组长度
uint lenth = initNums.length;

// 在内存中创建数组,注意,内存中只能创建定长数组
uint[] memory arr = new uint[](5);
// 定长数组不能使用push、pop方法,只能通过访问数组下标修改对应的值
arr[1] = 123;
}

function getArray() external view returns(uint[] memory) {
return initNums;
}
}

删除数组的两种方法

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;

contract ArrayShift {
uint[] public arr;

// 原理: 将i位置后面的元素左移1位,然后弹出最后一个元素.
// 优点: 剩余元素保持原有顺序 缺点: 太消耗gas费
function remove(uint _index) public {
require(_index < arr.length,"index out of bounds");
for (uint i = _index; i < arr.length; i++) {
arr[i] = arr[i + 1];
}
arr.pop();
}

// 方法二原理: 将要删除的元素和最后一个元素互换,然后pop出最后一个元素
// 优点: 节约gas 缺点: 会打乱数组原有的顺序
function remove2(uint _index) public {
arr[_index] = arr[arr.length - 1];
arr.pop();
}
}