我是javascript的新手,并试图在Google电子表格和邮件中使用邮件合并功能。我复制了教程脚本并进行了一些必要的更改(至少我能想到的)。但是当我尝试运行脚本时,我得到了TypeError:无法从null读取属性“length”。 (第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;
}
答案 0 :(得分:2)
如果正则表达式没有匹配项,templateVars
将为空。你需要在循环之前检查这个。
更新:
if (templateVars !== null) {
for (var i = 0; i < templateVars.length; i++) {
...
}
}
答案 1 :(得分:0)
我刚才遇到了同样的问题,但是我认为OP的问题与代码有关。
这是Google在其教程中提供的电子邮件模板的格式。
占位符为${"First Name"}
但是根据您编辑这些内容的方式,您可以获得${“First Name”}
,这是完全不同的
区别在于"
与“
一个是垂直(工作),另一个是&#34;斜体&#34; (没有工作)
有人知道计算机格式数据如何能够解释这一点的重要性,但只是打破了代码。