如何使用for循环大幅度减少代码长度? [英] How to use for loop to drastically reduce code length?

查看:160
本文介绍了如何使用for循环大幅度减少代码长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我使用for循环或其他方法来大大减少这段代码的长度吗?我只需要将某些数据从datAgg工作表复制到f5工作表,但是我想使用数组和for循环来完成此操作.我尝试了不同的时间,但这总是给我错误

Can someone help me to use a for loop or whatever to drastically reduce the length of this code? I just have to copy some data from datAgg sheet to f5 sheet, but I would like to do it using arrays and for loop. I tried different times but it always give me error

  function regValori(){
      var datAgg = 
      SpreadsheetApp.getActiveSpreadsheet().getSheetByName("dati 
      aggiornati");
      var f5 = 
      SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");
      var score1 = datAgg.getRange("P2").getValue(); // we want to store 
                                                        this
      //collecting names and values
      var Cname1=datAgg.getRange("A2").getValue();
      var score2 = datAgg.getRange("P3").getValue(); 
      var Cname2 = datAgg.getRange("A3").getValue();
      var score3 = datAgg.getRange("P4").getValue(); 
      var Cname3 = datAgg.getRange("A4").getValue();
      var score4 = datAgg.getRange("P5").getValue(); 
      var Cname4 = datAgg.getRange("A5").getValue();
      var score5 = datAgg.getRange("P6").getValue();
      var Cname5 = datAgg.getRange("A6").getValue();

      // get the row number where to put data
      // in correspodance with today date

      var riga = f5.getRange(2, 2).getValue();

      f5.getRange(2,3).setValue(Cname1);
      f5.getRange(2,4).setValue(Cname2);
      f5.getRange(2,5).setValue(Cname3);
      f5.getRange(2,6).setValue(Cname4);
      f5.getRange(2,7).setValue(Cname5);

     // this one to put the value for every day

     f5.getRange(riga, 3).setValue(score1);
     f5.getRange(riga, 4).setValue(score2);
     f5.getRange(riga, 5).setValue(score3);
     f5.getRange(riga, 6).setValue(score4);
     f5.getRange(riga, 7).setValue(score5);

}

推荐答案

我会这样做

function regValori(){
    var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
    var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");


    var riga = f5.getRange(2, 2).getValue();
    for (var i = 2; i <= 6; ++i) {
        f5.getRange(riga, i + 1).setValue(datAgg.getRange("P" + i).getValue());
        f5.getRange(2, i + 1).setValue(datAgg.getRange("A" + i).getValue());
    }

}

您需要做的就是使索引i从最低值到最高值,并为getRange()建立字符串.也不需要太多的中间变量或数组,因为您可以在一个循环中完成所有操作.

All you need to do is have the index i going from the lowest to the highest value and build the strings for getRange(). There's also no need for so many intermediary variables or an array, since you can do every operation in one loop.

这篇关于如何使用for循环大幅度减少代码长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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