我一直在编写以下函数,并且已经理解了直到这一行的所有内容。
cost += nightSurcharge;
我在 if
语句中使用条件,用于将夜间附加费添加到晚上 8 点到早上 6 点之间的费用中。
我需要了解的是,+=
是否只是简单地说,如果满足条件,则将 nightSurcharge 添加到成本中?
// add a parameter called hourOfDay to the function
var taxiFare = function (milesTraveled, hourOfDay) {
var baseFare = 2.50;
var costPerMile = 2.00;
var nightSurcharge = 0.50; // 8pm to 6am, every night
var cost = baseFare + (costPerMile * milesTraveled);
// add the nightSurcharge to the cost starting at
// 8pm (20) or if it is before 6am (6)
if (hourOfDay >= 20 || hourOfDay < 6) {
cost += nightSurcharge;
}
return cost;
};
最佳答案
What I need to understand is whether the
+=
is simply saying add the nightSurcharge to cost if the condition is met?
是的,that is exactly correct.此代码等效:
if (hourOfDay >= 20) {
cost = cost + nightSurcharge;
}
else if (hourOfDay < 6) {
cost = cost + nightSurcharge;
}
关于javascript - 不确定组合运算符在函数中执行什么操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955232/