4. Solidity:引用類型變量:數(shù)組

4.1 數(shù)組分類

  • 動(dòng)態(tài)數(shù)組(可變長(zhǎng)度數(shù)組)
    // 動(dòng)態(tài)數(shù)組
    uint[] public nums = [1,2,3];
    bytes public bs;
    address[] public addrs;
  • 定長(zhǎng)數(shù)組
    // 定長(zhǎng)數(shù)組
    uint[3] public nums3 = [1,2,3];
    bytes[3] public bs4;
    address[3] public addrs3;

4.2 數(shù)組操作

  • length: 獲取數(shù)組長(zhǎng)度
  • push() & push(x): 數(shù)組長(zhǎng)度+1,push() 為添加元素默認(rèn)值,push(x)為添加指定元素值
  • delete: 數(shù)組長(zhǎng)度不變,索引對(duì)應(yīng)元素置為默認(rèn)值
  • pop(): 數(shù)組元素-1,刪除末尾元素
    代碼示例:
    // 數(shù)組操作 
    function arrayOp() external returns (uint,uint,uint[] memory){
        // 獲取數(shù)組長(zhǎng)度
        uint a = nums.length;
        uint b = nums3.length;
 
        // push() & push(x)
        nums.push(); // 數(shù)組長(zhǎng)度增加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ù)組長(zhǎng)度(內(nèi)存中創(chuàng)建的數(shù)組為定長(zhǎng)數(shù)組)
    示例代碼:
    // 內(nèi)存中的數(shù)組
    function arrInMemory() pure external returns (uint, uint[] memory) {
        // 在內(nèi)存中創(chuàng)建數(shù)組,使用new關(guān)鍵字,數(shù)組必須指定長(zhǎng)度。(內(nèi)存中的數(shù)組必須為定長(zhǎng)數(shù)組)
        uint[] memory a = new uint[](3);

        // 內(nèi)存中數(shù)組的相關(guān)操作
        // 獲取數(shù)組長(zhǎng)度
        uint l = a.length;
        // 賦值
        a[0] = 1;
        a[1] = 2;
        a[2] = 3;
        // "刪除元素"
        delete a[1];

        return (l,a);
    }

4.4 數(shù)組元素刪除

Solidity中delete方法只會(huì)將數(shù)組中的元素置為默認(rèn)值,并不會(huì)將數(shù)組中的元素從數(shù)組中移出,即不會(huì)改變數(shù)組長(zhǎng)度。如果想刪除數(shù)組中的指定元素,根據(jù)業(yè)務(wù)需求不同,可以有移動(dòng)數(shù)組元素和替換數(shù)組元素兩種方法。

  • 移動(dòng)數(shù)組元素:適用于對(duì)數(shù)組元素順序有要求的情況(不改變數(shù)組元素順序,但是消耗較多gas fee)
    // 刪除數(shù)組元素--移動(dòng)數(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ù)組元素:適用于對(duì)于數(shù)組元素順序沒(méi)有要求的情況(消耗較少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;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容