Google 电子表格脚本不断写入空字符串

Google Spreadsheets Script Keeps Writing Empty Strings

我有一个 Google 表单提交到 Google 电子表格。在电子表格方面,我有一个 Google Apps 脚本,它应该加密提交的密码。但无论出于何种原因,它都会将一个空字符串写入加密密码所在的位置。这真的开始给我带来压力了。这是我的代码:

function encryptPassword(e) {
  var password = e.values[6];
  var split = password.split("");
  password = "";
  var char;

  for(char in split) {
    password = password.concat(getBinary(split[char]));
  }
  var spreadsheet = SpreadsheetApp.openById("1CywforbyBmPDHt2Uw9lJtyhqeklAAJp0IG7GfVV6U5U");
  spreadsheet.getRange("G" + spreadsheet.getLastRow().toString()).setValue(password);
  spreadsheet.getRange("H" + spreadsheet.getLastRow().toString()).setValue(password);
}

function getBinary(char) {
  var binary = "";
  var numValue;
  var range;
  var value;
  var chars = [
    ["#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"],
    ["@", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
    ["&", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"],
    ["%", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
    ["$", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  ];

  for(range in chars) {
    for(value in range) {
      if(value > 0) {
        if(char == chars[range][value]) {
          numValue = value - 1;
          binary = binary + chars[range][0];
          if(numValue / 8 >= 1) {
            numValue = numValue - 8;
            binary = binary.concat("1");
          } else {
            binary = binary.concat("0");
          }
          if(numValue / 4 >= 1) {
            numValue = numValue - 4;
            binary = binary.concat("1");
          } else {
            binary = binary.concat("0");
          }
          if(numValue / 2 >= 1) {
            numValue = numValue - 2;
            binary = binary.concat("1");
          } else {
            binary = binary.concat("0");
          }
          if(numValue / 1 >= 1) {
            binary = binary.concat("1");
          } else {
            binary = binary.concat("0");
          }
        }
      }
    }
  }
  return binary;
}

每当将表单提交到电子表格时,encryptPassword(e) 函数都会设置为 运行。另请注意,我已经修改了字符数组的内容,以试图使我的加密保密。不过,这应该没什么区别,因为其余代码保持不变。

如何修复我的脚本,使其实际上将加密密码而不是空字符串写入电子表格?

你有两个 For/In 循环:

for(range in chars) {
  for(value in range) {

A For/In 循环用于循环对象的属性。当您使用它来遍历数组时,就像您正在做的那样,"property" 是数组的索引号。

所以行:

for(range in chars) {

导致变量 range 在每个循环中都是一个数字值。在第一个循环中,range 的值为零。

第二个循环:

for(value in range) {

从不循环播放。没有什么可以循环的。变量 range 的值只是一个数字。您不能遍历单个数字。如果你使用调试器,你可以观察每一行在做什么,一次执行一行代码。

如果你想得到密码中某个字符的索引位置,你可以使用indexOf()。例如,如果密码中的字符是字母 "i".

var indexPosition = chars[2].indexOf(char);

indexPosition 的值将为 9。外部数组 chars 中的第三个数组在第 9 个索引位置有一个元素 "i"。