current position:Home>How to delete an element at a certain position in an array in solidity?

How to delete an element at a certain position in an array in solidity?

2022-02-03 20:47:15 Q & A of Denglian community

Solidity How to delete an element in an array at a certain position ?




Take the answer 1:

Solidity How to delete Array Element at a location in ?

Use delete The operator

delete Operators can delete elements :

delete array[index];

Move elements ( Optional )

But there will be an empty space above , If you remove this position first , You need to move the element manually :

contract test{    uint[] array = [1,2,3,4,5];    function remove(uint index)  returns(uint[]) {        if (index >= array.length) return;        for (uint i = index; i<array.length-1; i++){            array[i] = array[i+1];        }        delete array[array.length-1];        array.length--;        return array;    }}

If you don't care about the location of the element , You can copy the last element to the deleted element .

Reference documents

  1. Array member
  2. delete The operator

The original question link

Block chain in depth - Build a high-quality blockchain technology blog , All the school district chains come here , Focus on You know Microblogging .




copyright notice
author[Q & A of Denglian community],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/02/202202032047119452.html

Random recommended