类型错误:无法读取属性“长度";从空 [英] TypeError: Cannot read property "length" from null

查看:86
本文介绍了类型错误:无法读取属性“长度";从空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm very new with javascript and trying to play around with Mail Merge function in Google spreadsheet and mail. I copied the tutorial script and made some necessary changes (at least what I can think of). But when I tried to run the script, I got TypeError: Cannot read property "length" from null. (line 43)

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

The line 43 mentioned above is the for loop below. Can someone please help let me know what to be fixed so I can run the script?

// 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;
}

推荐答案

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

If there were no matches for the regular expression, templateVars will be null. You need to check for this before your loop.

更新:

if (templateVars !== null) {
    for (var i = 0; i < templateVars.length; i++) {
        ...
    }
}

这篇关于类型错误:无法读取属性“长度";从空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆