4.1 數(shù)組分類
- 動態(tài)數(shù)組(可變長度數(shù)組)
// 動態(tài)數(shù)組
uint[] public nums = [1,2,3];
bytes public bs;
address[] public addrs;
- 定長數(shù)組
// 定長數(shù)組
uint[3] public nums3 = [1,2,3];
bytes[3] public bs4;
address[3] public addrs3;
4.2 數(shù)組操作
- length: 獲取數(shù)組長度
- push() & push(x): 數(shù)組長度+1棉安,push() 為添加元素默認(rèn)值东跪,push(x)為添加指定元素值
- delete: 數(shù)組長度不變止喷,索引對應(yīng)元素置為默認(rèn)值
-
pop(): 數(shù)組元素-1呛凶,刪除末尾元素
代碼示例:
// 數(shù)組操作
function arrayOp() external returns (uint,uint,uint[] memory){
// 獲取數(shù)組長度
uint a = nums.length;
uint b = nums3.length;
// push() & push(x)
nums.push(); // 數(shù)組長度增加1彪杉,push元素為uint默認(rèn)值:[1,2,3] -> [1,2,3,0]
nums.push(5); // [1,2,3,0,5]
// delete
delete nums[1]; // [1,0,3,0,5]
// pop()
nums.pop(); // [1,0,3,0]
return (a,b,nums);
}
4.3 內(nèi)存中的數(shù)組
- 內(nèi)存中創(chuàng)建數(shù)組使用new關(guān)鍵字
- 必須指定數(shù)組長度(內(nèi)存中創(chuàng)建的數(shù)組為定長數(shù)組)
示例代碼:
// 內(nèi)存中的數(shù)組
function arrInMemory() pure external returns (uint, uint[] memory) {
// 在內(nèi)存中創(chuàng)建數(shù)組谣光,使用new關(guān)鍵字檩淋,數(shù)組必須指定長度。(內(nèi)存中的數(shù)組必須為定長數(shù)組)
uint[] memory a = new uint[](3);
// 內(nèi)存中數(shù)組的相關(guān)操作
// 獲取數(shù)組長度
uint l = a.length;
// 賦值
a[0] = 1;
a[1] = 2;
a[2] = 3;
// "刪除元素"
delete a[1];
return (l,a);
}
4.4 數(shù)組元素刪除
Solidity中delete方法只會將數(shù)組中的元素置為默認(rèn)值萄金,并不會將數(shù)組中的元素從數(shù)組中移出蟀悦,即不會改變數(shù)組長度。如果想刪除數(shù)組中的指定元素氧敢,根據(jù)業(yè)務(wù)需求不同日戈,可以有移動數(shù)組元素和替換數(shù)組元素兩種方法。
- 移動數(shù)組元素:適用于對數(shù)組元素順序有要求的情況(不改變數(shù)組元素順序孙乖,但是消耗較多gas fee)
// 刪除數(shù)組元素--移動數(shù)組元素
function remove1(uint _index) external returns (uint[] memory) {
require(_index < nums.length, "index out if range");
for (uint i = _index;i < nums.length - 1;i++) {
nums[i] = nums[i+1];
}
nums.pop();
return nums;
}
- 替換數(shù)組元素:適用于對于數(shù)組元素順序沒有要求的情況(消耗較少gas fee浙炼,但是改變了數(shù)組元素順序)
// 刪除數(shù)組元素--替換數(shù)組元素
function remove2(uint _index) external returns (uint[] memory){
require(_index < nums.length, "index out if range");
nums[_index] = nums[nums.length - 1];
nums.pop();
return nums;
}