【问题标题】:How to remove an array elemet from a certain prosition in solidity?如何从solidity中的某个位置删除数组元素?
【发布时间】:2022-09-24 15:35:05
【问题描述】:

有没有像 array.remove 或类似的方法从某个位置删除一个元素,它不会留下一个间隙。

    标签: arrays ethereum solidity


    【解决方案1】:

    并非不留空隙。

    要从数组中删除一个项目,您需要将所有后续项目向左移动,并删除最后一个项目。

    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;
        }
    }
    

    【讨论】:

    • 是否有任何方法可以删除元素并自动移动所有项目,或者我必须一直手动执行
    • @BappiRahman 没有本机方法(v0.8.11)。
    【解决方案2】:

    只需交换元素并弹出

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 2019-01-05
      • 2011-11-23
      • 2022-03-19
      • 2011-06-25
      • 1970-01-01
      相关资源
      最近更新 更多