首页 > 解决方案 > 我可以在 Google Apps Script MailApp 中执行条件语句吗?

问题描述

我认为这会相当简单,但我不能有条件地在 MailApp 中工作。我想要做的就是通过电子邮件发送一个由表单创建的地址,如果有一个“address2”条目来添加该行。如果没有条件,大多数地址在电子邮件中都会有换行符。我想要类似于下面代码的东西,但 Google Script 不会让我保存它,因为 if 语句会引发语法错误。

MailApp.sendEmail({
to: "johndoe@gmail.com",
subject: "New Client",
htmlBody: "<p>New Client</p>" +
    "<p>Contact Name: " + ContactName + "<br>" +
    "Address:<br>" +
    "<br>" +
    address1 + "<br>" +
if(address2 !== 0)
    {address2 + "<br>" +}
    city + "," + state + zip "</p>".
});

请指教。谢谢。

标签: google-apps-scriptconditional

解决方案


"<br>" + if(address2 !== 0) {address2 + "<br>" +} city + "," + state + zip "</p>"

不是有效的 JavaScript。if 语句不是可以在公式中使用的运算符;这就是三元运算符condition ? if_true : if_false的用途。例子:

"<br>" + (address2 !== 0 ? address2 + "<br>" : "") + city + "," + state + zip + "</p>"

推荐阅读