【发布时间】:2022-09-24 15:35:05
【问题描述】:
有没有像 array.remove 或类似的方法从某个位置删除一个元素,它不会留下一个间隙。
有没有像 array.remove 或类似的方法从某个位置删除一个元素,它不会留下一个间隙。
并非不留空隙。
要从数组中删除一个项目,您需要将所有后续项目向左移动,并删除最后一个项目。
pragma solidity ^0.8;
contract MyContract {
uint256[] array = [100, 200, 300, 400, 500];
function remove(uint256 index) external {
require(array.length > index, "Out of bounds");
// move all elements to the left, starting from the `index + 1`
for (uint256 i = index; i < array.length - 1; i++) {
array[i] = array[i+1];
}
array.pop(); // delete the last item
}
function getArray() external view returns (uint256[] memory) {
return array;
}
}
【讨论】:
只需交换元素并弹出
pragma solidity ^0.8;
contract MyContract {
uint256[] arr = [1, 2, 3, 4, 5];
function remove(uint256 index) external {
uint temp = arr[index];
arr[index] = arr[arr.length-1]
arr[arr.length-1] = temp;
// pop index
array.pop();
}
function getArray() external view returns (uint256[] memory) {
return array;
}
}
【讨论】: