我有以下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
我哪里错了?
答案 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)
让我们进行迭代:
totals = 21;
paginatorval = 5;
fetched = 0;
i = 0;
fetched => 5
console.log(5);
i => 5
totals = 21;
paginatorval = 5;
fetched = 5;
i = 5;
fetched => 10
console.log(10);
i => 10
totals = 21;
paginatorval = 5;
fetched = 10;
i = 10;
fetched => 15
console.log(15);
i => 15
totals = 21;
paginatorval = 5;
fetched = 15;
i = 15;
fetched => 21 // !!! because (15 > (21-15)) is true
console.log(21);
i => 20
totals = 21;
paginatorval = 5;
fetched = 21;
i = 20;
fetched => 22 // !!! because (20 > (21-20)) is true
console.log(22);
i => 25
正如您所看到的,“循环3”中的所有内容都会中断,因为您的if
语句将转到另一个分支。这与打字稿无关,但