Ethereum Asked by Alejandro Veintimilla on November 7, 2021
I’m having trouble understanding why people call
array.length--
after deleting an element in an array (as seen in this answer and many others). Why is there need for doing so? When is the length of an array evaluated? Or maybe I’m missing something obvious, what does array.length--
actually do?
You must use array.length--
in order to accurately persist the length of the array.
The confusion comes from the fact that delete
in Solidity does not actually delete an element from an array, but rather it just sets the element to it's default value (0
for a uint256
, for example).
Observe the following code as an example:
uint256[] public testArray = [1,2,3,4,5];
// testArray = [1,2,3,4,5]
// testArray.length = 5
delete testArray[4];
// testArray = [1,2,3,4,0]
// testArray.length = 5
testArray.length--
// testArray = [1,2,3,4]
// testArray.length = 4
Answered by Shane Fontaine on November 7, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP