【问题标题】:if statement to check if user is authorized based on emailif 语句检查用户是否基于电子邮件获得授权
【发布时间】:2020-04-27 19:00:41
【问题描述】:

我对使用 Google Apps 脚本进行编码非常陌生。

我正在尝试创建一个函数,当用户单击按钮时,该函数将在 Google 工作表上创建时间戳,但前提是用户的电子邮件地址包含在工作簿中另一个工作表的范围内。

作为参考,列出用户电子邮件地址的选项卡称为“制造商”,该列表位于 A 列中。

目前,该功能在用户电子邮件地址位于列表的单元格 A2 中的地方工作,但是如果它位于列表中的其他任何位置(例如 A3),则脚本会抛出我编写的错误。

只要用户被授权(在列表中),代码就应该在另一个标签上标记他们的电子邮件地址以及他们的操作日期和时间。

这是我的代码:

  var ss = SpreadsheetApp.getActiveSheet();
  var usr = Session.getActiveUser().getEmail();
  var DateTime = new Date();
  var emails = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Makers").getRange("A2:A").getValues();


for (var i=0;i<emails.length;i++) {
  if (emails[i][0] === usr){
    ss.getRange('B3').setValue(usr);
    ss.getRange('C3').setValue(DateTime).setNumberFormat('dd/MM/yyyy HH:mm:ss');
    return;
  } else {
  SpreadsheetApp.getUi().alert('You are not authorised to perform that action');
  throw new Error('You are not authorised to perform that action');
   }
 }

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript arrays google-apps-script google-sheets


    【解决方案1】:
    if (emails[i][0] === usr){ } else { throw new Error('You are not authorised')}
    

    这里的if 语句指出,如果当前处于循环中的电子邮件emails[i][0] 不是usr,则抛出一个新错误。因此,如果检查的第一封电子邮件不是usr,它将引发错误。由于您已经有一个 return 来结束函数,因此当找到匹配项时,您不需要 else 语句。应该在循环外抛出错误:

    for (var i=0;i<emails.length;i++) {
      if (emails[i][0] === usr){
        /*stuff*/
        return;
      }
     }//end for -loop
    /*function not yet `return`ed. No email is matched. Time to Throw*/
    SpreadsheetApp.getUi().alert('You are not authorised to perform that action');
    throw new Error('You are not authorised to perform that action');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-05
      • 2012-08-20
      • 2012-10-26
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多