简体   繁体   English

使用 javascript 在 FOR 循环中选择批次的百分比

[英]Selecting a percentage % of a batch in FOR loop using javascript

I am working with javascript and i have a loop that selects all the data rows.我正在使用 javascript,我有一个循环来选择所有数据行。

The number of rows can be different each time and I do not want to select ALL rows at a time.每次的行数可能不同,我不想一次选择所有行。 I want to get rows in 10% batches so performance is better.我想以 10% 的批次获取行,以便性能更好。

Currently i am trying this approach but needs your suggestion is this is a right approach or if there is any better approach?目前我正在尝试这种方法,但需要您的建议,这是一种正确的方法还是有更好的方法?

   var TenPercBatch = 0.1;

//  for (i in data) {   
     for (var i = 0; i < data.length*TenPercBatch; ++i) {
       var row = data[i];
    var emailAddress = row[0];  // First column     
    var emailSent = row[1]; // Second column

   if (emailSent != EMAIL_SENT) { // Prevents sending duplicates   

    //PRODUCTION EMAIL FORM LINK
     var url = "https://www.mysiteformurl-endpoint.com"; 
    UrlFetchApp.fetch(url + '&EMAILADDRESS=' + encodeURIComponent(emailAddress));

    AudienceList.getRange(startRow + i, 2).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
   }

} }

Depending on number of rows, there are times when i get output in decimal when i calculate 10% of something manually...like 1000 rows, 10% would be 100..but if I have 5 rows, 10% would be 0.5.根据行数,有时当我手动计算某些内容的 10% 时,我会得到十进制输出......比如 1000 行,10% 将是 100 ..但如果我有 5 行,10% 将是 0.5。 Is there any way to get the output in non-decimal closest number only so there are no issues in the code?有没有办法只以非十进制最接近的数字获得输出,所以代码中没有问题?

Like...if 10% is 0.5 then use 1.....if 10% is 7.5 then select 8...and so on...就像...如果 10% 是 0.5 然后使用 1.....如果 10% 是 7.5 然后选择 8...等等...

Is it possible?是否可以?

Another question is - How to select next 10% only?另一个问题是 - 如何仅选择下一个 10%? As I am looking at my loop, I am thinking it MAY always select same 10% batch.当我查看我的循环时,我认为它可能总是选择相同的 10% 批次。

In math there is a function called ceiling with always rounds non-whole numbers to the next integer, eg Math.ceil(3) == 3 and Math.ceil(3.1) == 4 .在数学中,有一个函数被称为天花板,它总是将非整数四舍五入到下一个整数,例如Math.ceil(3) == 3Math.ceil(3.1) == 4

To be safe, you best want to do something like this, although I am unsure as to why you would want to do this in general.为了安全起见,您最好做这样的事情,尽管我不确定您为什么要这样做。

for(var a = 0; a < 10; a++)
{
    for(var i = Math.floor(a*data.length*0.1); i < data.length && i < Math.ceil((a+1)*data.length*0.1); i++)
    {
        //do stuff within batch
    }

    //do stuff in between batches
}

The inner loop iterates of the the a-th 10% of the data object.内部循环迭代数据对象的第 a-10%。 If you just want to iterate over the first 10% just set a to 0 instead of the outer for-loop.如果您只想迭代前 10%,只需将 a 设置为 0 而不是外部 for 循环。

当然可以,使用Math.ceil( )函数 :)

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

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