1

我对 javascript 非常陌生,并试图在 Google 电子表格和邮件中使用邮件合并功能。我复制了教程脚本并进行了一些必要的更改(至少我能想到的)。但是当我尝试运行脚本时,我得到了 TypeError: Cannot read property "length" from null。(第 43 行)

上面提到的第 43 行就是下面的 for 循环。有人可以帮我知道要修复什么,以便我可以运行脚本吗?

// Replaces markers in a template string with values define in a JavaScript data object.
// Arguments:
//   - template: string containing markers, for instance ${"Column name"}
//   - data: JavaScript object with values to that will replace markers. For instance
//     data.columnName will replace marker ${"Column name"}
// Returns a string without markers. If no data is found to replace a marker, it is
// simply removed.
function fillInTemplateFromObject(template, data) {
    var email = template;
    // Search for all the variables to be replaced, for instance ${"Column name"}
    var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
    // Replace variables from the template with the actual values from the data object.
    // If no value is available, replace with the empty string.
    for (var i = 0; i < templateVars.length; ++i) {
        // normalizeHeader ignores ${"} so we can call it directly here.
        var variableData = data[normalizeHeader(templateVars[i])];
        email = email.replace(templateVars[i], variableData || "");
    }
    return email;
}
4

2 回答 2

2

如果正则表达式没有匹配项,则为templateVarsnull。您需要在循环之前检查这一点。

更新:

if (templateVars !== null) {
    for (var i = 0; i < templateVars.length; i++) {
        ...
    }
}
于 2012-10-18T07:58:24.340 回答
0
于 2014-11-30T08:37:38.863 回答