简体   繁体   English

如何在 for 循环中使用 I-Value

[英]How to use I-Value in for-loop

Hi I am playing around with javascript and firebase but running into an issue.嗨,我正在使用 javascript 和 firebase,但遇到了一个问题。

I want to sent the same email to every email listed in my datebase after the database entry hast been created:在创建数据库条目后,我想向我的数据库中列出的每封电子邮件发送相同的电子邮件:

在此处输入图片说明

If I use the code without the for-loop everything works fine:如果我使用没有 for 循环的代码,一切正常:

to: snap.data().email,

I tried a few ways to use the i-value as an argument - one of them not working is in the code below:我尝试了几种方法来使用 i 值作为参数 - 其中一个不起作用的是在下面的代码中:

to: snap.data().email.concat(i.toString()),
exports.sendEmail = functions.firestore
    .document('user/{userId}')
    .onCreate((snap, context) => {

      for(var i = 1; i <= snap.data().number; i++) {
        const mailOptions = {

            from: `***********`,
            to: snap.data().email.concat(i.toString()),
            subject: `From ${snap.data().name}`,
            html: `<h1>Me ${snap.data().name} </h1>
                                <p>
                                   <b>Hallo - </b>${snap.data().content}<br>
                                </p>`
      };
      return transporter.sendMail(mailOptions, (error, data) => {
          if (error) {
              console.log(error)
              return
          }
          console.log("sent")
      });
    };

    });

I would really appreciate if you could help me out :-)如果您能帮助我,我将不胜感激:-)

if you want to get email1 , and email2 , ... properties, you can do as below如果你想获得email1email2 ,...属性,你可以做如下

to: snap.data()['email'+i],

also to have better code, you can store snap.data() into a variable like为了获得更好的代码,您可以将snap.data()存储到一个变量中,例如

const data = snap.data();

and use it over and over like并一遍又一遍地使用它

to: data['email'+i]

Also you have return in your loop, it means after first one it will exit loop你也有return在你的循环中,这意味着在第一个之后它将退出循环

Suggestion建议

You can store emails as an array, instead of one by one, then you can simply loop through and send emails, also then you don't need number, so you shape of data will be like您可以将电子邮件存储为一个数组,而不是一个一个,然后您可以简单地循环并发送电子邮件,然后您不需要数字,因此您的数据形状将像

{
  content: string;
  name: string;
  emails: string[];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM