Solidity

將 bytes32 值從映射複製到數組

  • July 10, 2018

我正在嘗試將儲存的值從映射複製到數組。我有以下程式碼:

pragma solidity ^0.4.21;

contract test {

event LogTest(
   bytes32[5] a
); 

bytes32[5]  arr;    
mapping (uint=>bytes32) attr;

//function that stores values and copies them to array which is returned
function attributes() internal returns(bytes32[5]){
   bytes32[5] x;
   attr[0] = "0x0"; attr[1] = "0x1"; attr[2] = "0x2"; attr[3] = "0x3"; attr[4] = "0x4";

   for(uint i=0;i<5;i++){
       x[i] = attr[i];
   }
   return(x);
}

//function that retrieves stored values and prints them in log
function copy() public {
   arr = attributes();
   LogTest(arr);
}    

}

出於某種原因,我沒有複製正確的值。我得到的東西看起來像這樣:

"event": "LogTest",
       "args": {
           "0": [
               "0x3078300000000000000000000000000000000000000000000000000000000000",
               "0x3078310000000000000000000000000000000000000000000000000000000000",
               "0x3078320000000000000000000000000000000000000000000000000000000000",
               "0x3078330000000000000000000000000000000000000000000000000000000000",
               "0x3078340000000000000000000000000000000000000000000000000000000000"]
  1. 我究竟做錯了什麼?這些值甚至沒有永久儲存在attributes()函式中嗎?
  2. 有沒有比儲存在地圖中並複製到數組中更好的方法?
  1. 我究竟做錯了什麼?這些值甚至沒有永久儲存在 attributes() 函式中嗎?

您正在保存單詞 0x0、0x1 等的字節表示形式:attr[0]=0x0而不是attr[0]="0x0"(省略引號)。就這些。

  1. 有沒有比儲存在地圖中並複製到數組中更好的方法?

這取決於你在做什麼。您可以直接保存在陣列上。

希望這可以幫助。

引用自:https://ethereum.stackexchange.com/questions/52995