我一直在编写以下函数,并且直到这一行才能理解所有内容。
cost += nightSurcharge;
我在我的if
语句中使用条件,用于在晚上8点到早上6点之间将nightSurcharge添加到成本中。
我需要了解的是+=
是否只是说如果满足条件,则将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;
};
答案 0 :(得分:3)
我需要了解的是
+=
是否只是说如果满足条件,则将nightSurcharge添加到成本中?
是的,that is exactly correct.此代码是等效的:
if (hourOfDay >= 20) {
cost = cost + nightSurcharge;
}
else if (hourOfDay < 6) {
cost = cost + nightSurcharge;
}