如何从for循环的每次迭代返回值

时间:2015-09-08 09:40:52

标签: javascript loops google-apps-script

这篇文章旨在列出一份电子表格数据列表,并发送一份HTML格式的电子邮件,并将该数据发送到我的电子邮件地址。 CODE.GS是将变量传递给INDEX.HTML因此可以将其格式化为HTML模板。日期:09/09/2015 JFKAESE @ GMAIL。 COM

CODE.GS

// THIS FUNCTION TAKES THE ITERATOR VARIABLE TO GO DOWN SHEET DATA
function emailBody(i){

  //GET SPREADSHEET BY ID AND SHEET NAME
  var ss = SpreadsheetApp.openById('1Wc0j3twn1i-ug-lCsWOxyk-8u9t21Vr_xJH9wVu4KTk');
  var sheet = ss.getSheetByName('Sheet1');

  // GET DATA AND RETURN IT FOR THE HTML BODY
  var item1 = sheet.getRange(i,1).getValue();
  var item2 = sheet.getRange(i,2).getValue();
  return [item1, item2];

} 

// THIS FUNCTION LOOPS < 5 FOR TESTING PURPOSES BUT SHOULD GO
// UNTIL THE LAST ROW OF DATA

function looper() {
  for (var i = 1; i < 5; i++){

    // LOG THE OUTCOME -- WORKING PERFECT.
    // I NEED TO SEND THE DATA TO THE INDEX.HTML FOR FORMATTING
    Logger.log(emailBody(i));
  }
}

// THIS FUNCTION IS TO SEND THE EMAILS TO MY EMAIL ADDRESS
function sendEmails() {
  var template = HtmlService.createTemplateFromFile('Index');
  var body = template.evaluate().getContent();

  // SEND THE EMAIL
  MailApp.sendEmail({
    subject:"Test Email",
    to:"example@domain.com",
    htmlBody: body,
  });
}

INDEX.HTML

<!DOCTYPE html>

<html>

  <body style="background-color:#F5F5F5">


    <p><? var data = emailBody(); ?></p>
    <p><? var item1 = data[0]; ?></p>
    <p><? var item2 = data[1]; ?></p>
    <p><?= item1 ?>
    <p><?= item2 ?>

  </body>

</html>

2 个答案:

答案 0 :(得分:1)

稍微更改一下函数定义并在循环内调用它。这就是为每次迭代返回两个值的方法。

 function emailBody(i){
          var ss = SpreadsheetApp.openById('A_SHEET_ID_HERE');
          var sheet = ss.getSheetByName('Sheet1');


            var item1 = sheet.getRange(i,1).getValue();
            var item2 = sheet.getRange(i,2).getValue();
            return [item1, item2];


        } 
 for (var i = 1; i < 5; i++){
    console.log( emailBody(i));
    }

为了传递价值,您可以这样做,您希望如何获得价值取决于您:

<强> HTML

<p id="item1"></p>
<p id="item2"></p>

<强> JAVASCRIPT

document.getElementById("item1").innerHTML=item1;
document.getElementById("item2").innerHTML=item2;

答案 1 :(得分:0)

将您想要返回的项存储到变量中,以便for循环可以完成执行,然后执行return语句,并在for循环结束时传递变量?