我有一个数组,如果它是第一个元素,我必须使用与数组中其余元素相比的不同公式进行计算。问题是循环只进入if条件而没有进入else条件。
不确定我是否正确行事。
以下是代码:
var days = 535; //user selection
var val = 3; //user selection
var baseDays = 182.5;
var someValArr_1 = [12,16,23,31,33,34,39,45,49,54,59,62,62,so on]; //same for 2 other arrays
var someValArrDiff_1 = diff(someValArr_1); //function to subtract two consecutive elements in array
var noOfDays =[182.5,365,547.5,730,912.5,so on];
var arrayLength = noOfDays.length;
for (var i = 0; i < arrayLength; i++) {
if(noOfDays[i] == noOfDays[0]) { //182.5
switch(val) {
case 1:
discount = days/noOfDays[i] * someValArrDiff_1[i];
break;
case 2:
discount = days/noOfDays[i] * someValArrDiff_2[i];
break;
case 3:
discount = days/noOfDays[i] * someValArrDiff_3[i];
break;
default:
break;
}
}
else {
if(noOfDays[i] < days && days < noOfDays[i+1]){
switch(val) {
case 1:
discount = (days-noOfDays[i]) * someValArrDiff[i+1]/baseDays + someValArr_1[i];
break;
case 2:
discount = (days-noOfDays[i]) * someValArrDiff_2[i+1]/baseDays + someValArr_2[i];
break;
case 3:
discount = (days-noOfDays[i]) * someValArrDiff_3[i+1]/baseDays + someValArr_3[i];
break;
default:
break;
}
}
}
console.log("Discount " +discount);
return discount;
}
我尝试if(days < noOfDays[0])
,但这会完全跳过if-else条件并返回0.
答案 0 :(得分:1)
for (var i = 0; i < arrayLength; i++) {
应该是
for (var i = 0; i < arrayLength - 1; i++) {
因为下面的陈述会将535与未定义的
进行比较if(noOfDays[i] < days && days < noOfDays[i+1]){
第二件事是你可以安全地改变
if(noOfDays[i] == noOfDays[0])
到
if(i === 0)
答案 1 :(得分:1)
在此代码中,i
将被设置为数组中第一个元素的索引,大于days
。
var days = 535;
var noOfDays =[182.5,365,547.5,730,912.5];
var i = 0;
while (days > noOfDays[i]) i++;
if (i == 0) {
// do your calculation for days <= 182.5
} else {
// do your calculation for days between noOfDays[i-1] and noOfDays[i]
}
这将删除您所拥有的错误(在迭代一次循环后返回)并删除不必要地计算直到i的所有内容的折扣,这将被丢弃。