0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Solidity】(tips)配列において指定の数字を削除する

Posted at

配列において指定の数字を削除する方法を下記します。
solidityにでは、配列の削除に関してdeleteを使用すると0になるのみです。
なので、完全に数字を削除するためには、工夫が必要です。
具体的にはremove関数で実装しています。
remove関数の中身は、削除したい指定した番号を、次の番号に置き換え、popで最後の配列の数字を削除しています。
例えばremove関数に2を引数として渡した場合numbersの中身は、
[1,2,3,4,5,6]
→[1,2,4,5,6,6] ※2番目の数字以降を次の数字に置き換える
→[1,2,4,5,6] ※popで最後の数字を削除する

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

contract Sample{
    uint[] public numbers = [1,2,3,4,5,6];

    function getNumbers()public view returns(uint[] memory){
        return numbers;
    }

    function getNumberLen()public view returns(uint){
        return numbers.length;
    }
    
    function deleteNumber(uint _index)public {
        delete numbers[_index];
    }

    //
    function remove(uint _index) public {
        require(_index < numbers.length, "over length");

        for (uint i = _index; i < numbers.length - 1; i++) {
            numbers[i] = numbers[i + 1];
        }
        numbers.pop();
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?