在JavaScript中循环和增量

时间:2018-01-17 11:29:30

标签: javascript while-loop increment

在下面的函数中,我需要增加years变量,以便找到在达到预期利润之前需要经过的年数。我注意到,如果我使用years++而不是++years,则此功能无效。我理解两种增量方法之间的区别,但是,我仍然不理解,在这种特殊情况下years++导致循环只执行一次。

 function calculateYears(investment, interestRate, tax, desiredProfit) {
        var years = 0;
        while(investment < desiredProfit && ++years){
          investment += (investment * interestRate) * (1 - tax);
        }
    
        return years;
    }
    var years = calculateYears(1000, 0.05, 0.18, 1100);
    console.log(years);

7 个答案:

答案 0 :(得分:4)

它只执行一次,因为用于检查真实性的years的值是0,即在递增之前。

MDN Documentation

答案 1 :(得分:3)

  

我仍然不明白,在这个特殊情况下,几年++会导致   循环只执行一次。

因为&& years++会转换为&& 0,会转换为 falsey value

如果您想使用years++,请将years初始化为1

function calculateYears(investment, interestRate, tax, desiredProfit) {
    var years = 1;
    while(investment < desiredProfit && years++){
      investment += (investment * interestRate) * (1 - tax);
    }

    return years - 1;
}
console.log(calculateYears(1000, 0.05, 0.18, 1100));

答案 2 :(得分:2)

你应该在循环中使用years++

function calculateYears(investment, interestRate, tax, desiredProfit) {
    var years = 0;
    while(investment < desiredProfit){
      investment += (investment * interestRate) * (1 - tax);
      years++;
    }

    return years;
}
alert(calculateYears(1000, 0.05, 0.18, 1100));

<强> JSFIDDLE

答案 3 :(得分:0)

while(investment < desiredProfit && ++years)

这个条件不会执行,因为年份是0,它在1循环后递增,所以它就像

desiredProfit && 0 -> false/0

之后

investment < 0 //is always false

答案 4 :(得分:0)

你确实忘记了你的while循环没有增加年数值

 while(investment < desiredProfit && ++years){
  investment += (investment * interestRate) * (1 - tax); years++;
}

答案 5 :(得分:0)

为什么不做这样的事情

let i = -6;
let end = 9;
while ((i++ || true) && i < end) {
...do something...
}

答案 6 :(得分:-1)

因为&& years++会转换为&& 0,这会转换为假值。

如果您想使用years++,请将年份初始化为1。