打字稿"做什么"出乎意料的结果

时间:2017-10-04 22:12:33

标签: javascript typescript

我有以下while循环:

  onTryExport(dt?:DataTable){
    const totals = 21;//this.totalRecords;
    const paginatorval = 5;//this.paginatorval;
    const fetched = 0;
    const i =0;

   do{

      if ( i > (totals-i) ) {

     fetched+=(totals-i); //executed twice

    }else{

       fetched+=paginatorval;
   }

     console.log(fetched);
     i+= paginatorval;

 }while(i<totals);
}

abopve console.log()输出

5, 10, 15,21,22

我的期望

5,10,15,20,21

我哪里错了?

2 个答案:

答案 0 :(得分:2)

我认为这是你真正想要的?

而不是:if ( i > (totals - i) ) {

尝试:if ( i > (totals - paginatorval) ) {

const totals = 21;//this.totalRecords;
const paginatorval = 5;//this.paginatorval;
const fetched = 0;
const i = 0;

do {
  if ( i > (totals - paginatorval) ) {
    fetched += (totals - i); //asdf
  } else {

    fetched+=paginatorval;

  }

  console.log(fetched);

  i += paginatorval;

} while(i < totals);

答案 1 :(得分:1)

让我们进行迭代:

周期0

totals = 21; 
paginatorval = 5;
fetched = 0;
i = 0;
fetched => 5
console.log(5);
i => 5

第1周期

totals = 21; 
paginatorval = 5;
fetched = 5;
i = 5;
fetched => 10
console.log(10);
i => 10

第2周期

totals = 21; 
paginatorval = 5;
fetched = 10;
i = 10;
fetched => 15
console.log(15);
i => 15

第3周期

totals = 21; 
paginatorval = 5;
fetched = 15;
i = 15;
fetched => 21 // !!! because (15 > (21-15)) is true
console.log(21);
i => 20

周期4

totals = 21; 
paginatorval = 5;
fetched = 21;
i = 20;
fetched => 22 // !!! because (20 > (21-20)) is true
console.log(22);
i => 25

正如您所看到的,“循环3”中的所有内容都会中断,因为您的if语句将转到另一个分支。这与打字稿无关,但