【问题标题】:Use custom MD5 formula with ARRAYFORMULA使用带有 ARRAYFORMULA 的自定义 MD5 公式
【发布时间】:2019-03-08 08:29:16
【问题描述】:

我实现了此处提到的 MD5 公式:Hash of a cell text in Google Spreadsheet

function MD5 (input) {
  var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
  Utilities.sleep(100)
  var txtHash = '';
  for (i = 0; i < rawHash.length; i++) {
    var hashVal = rawHash[i];
    if (hashVal < 0) {
      hashVal += 256;
    }
    if (hashVal.toString(16).length == 1) {
      txtHash += '0';
    }
    txtHash += hashVal.toString(16);
  }
  return txtHash;
}

现在我想用ARRAYFORMULA 运行它,但我无法让它工作。我试过这个:

=ARRAYFORMULA(({"FiBu MD5";IF(ISBLANK(AG2:AG),"",(MD5(O2:O)))}))

我得到的错误是:

“无法将 Array 转换为 (class)[]。(第 2 行)。”

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: google-apps-script google-sheets md5 array-formulas custom-function


    【解决方案1】:

    这个修改怎么样?

    例如使用你问题的当前脚本时,在MD5(O2:O)作为自定义函数的情况下,function MD5(input) {}input是像[[value of O2], [value of O3],,,]这样的二维数组。但是在您的脚本中,结果是通过输入一个不是数组的值返回的。这样,您的问题中显示的错误就会发生。所以为了输入和输出数组,需要针对这种情况修改脚本如下。

    修改脚本:

    function MD5(input) {
      for (var i = input.length - 1; i >= 0; i--) {
        if (input[i][0]) {
          input.splice(i + 1);
          break;
        }
      }
      var result = input.map(function(e) {
        if (e[0] != "") {
          var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, e[0]);
      //    Utilities.sleep(100) // I thought that this might be not required.
          var txtHash = '';
          for (i = 0; i < rawHash.length; i++) {
            var hashVal = rawHash[i];
            if (hashVal < 0) {
              hashVal += 256;
            }
            if (hashVal.toString(16).length == 1) {
              txtHash += '0';
            }
            txtHash += hashVal.toString(16);
          }
          return [txtHash];
        }
        return [];
      });
      return result;
    }
    

    注意:

    • 我认为通过上面的修改,你也可以使用={"FiBu MD5";MD5(O2:O)}的公式来代替=ARRAYFORMULA(({"FiBu MD5";IF(ISBLANK(AG2:AG),"",(MD5(O2:O)))}))

    如果这不起作用,我深表歉意。当时,为了正确了解您的情况,能否提供一个样本Spreadsheet?通过这个,我想修改脚本。

    【讨论】:

    • @moritz 很高兴您的问题得到了解决。也谢谢你。
    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 2020-03-02
    • 2021-10-16
    • 2021-12-25
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多