0

基于https://www.plivo.com/blog/Send-templatized-SMS-from-a-Google-spreadsheet-using-Plivo-SMS-API/我有以下代码:

data = {
    "SOURCE" : "+1234567890",
    "DESTINATION" : "+2345678901",
    "FIRST_NAME" : "Jane",
    "LAST_NAME" : "Doe",
    "COUPON" : "DUMMY20",
    "STORE" : "PLIVO",
    "DISCOUNT" : "20",
}

template_data = "Hi   FIRST_NAME , your coupon code for discount of % purchase at  is "

function createMessage(data,template_data){
  Logger.log(data);

  for (var key in data) {
    Logger.log(key);

    if (data.hasOwnProperty(key)) {
      template_data = template_data.replace(new RegExp('+key+', 'gi'), data[key]);
    }
  }
  Logger.log(template_data);
  return template_data;
}

当我运行createMessage并检查日志时,我看到:

[18-10-02 13:19:03:139 EDT] undefined
[18-10-02 13:19:03:139 EDT] undefined

这向我表明参数没有被传递到函数中。我究竟做错了什么?

4

1 回答 1

1

在脚本编辑器中运行函数不会将参数传递给函数。目前,您的项目的全局命名空间中有 3 个用户对象(其中包括来自 Google 的其他对象):

  • createMessage(一个函数对象)
  • template_data(一个字符串)
  • data(一个东西)。

该行将function createMessage(data, template_data)对象声明createMessage为函数对象,并指示传递给函数的前两个参数在函数范围内分别为datatemplate_data。这些函数范围的参数声明隐藏了任何更远的声明(即来自全局范围或封闭函数范围)。

然后解决方案是编写一个您实际执行的“驱动程序函数”,在其中定义被调用函数的输入参数,或者从函数调用中删除参数:

var data = {...}; // global var
var template_data = {...}; // global var
function driver() {
  createMessage(data, template_data); // uses the globally scoped `data` & `template_data` objects
  var otherdata = 1,
      otherTemplate = 2;
  createMessage(otherdata, otherTemplate); // uses the function-scoped `otherdata` and `template_data` objects
}
function createMessage(someData, someTemplate) {
  Logger.log(someData);
  Logger.log(arguments[0]); // equivalent to the above line.
  // ...
}

避免参考阴影:

function createMessage() { // removed `arguments` reference binding
  Logger.log(data);  // accesses global-scope `data` object because there is no `data` reference in the nearest scope

为了帮助解决这种情况 - 防止通过需要参数的函数的脚本编辑器手动执行 - 我通常会通过_在名称中添加尾随来使函数私有:function cantBeRunManually_(arg1, arg2, arg3) { ... }

参考:

于 2018-10-02T17:44:24.673 回答