2009-11-22 44 views

回答

5

沒有必要使用for循環:

function calculateFee(hours) { 
    if (isNaN(hours) || hours <= 0) return 0; 
    if (hours <= 3) return 2; 
    var additionalHours = Math.round(hours - 3); 
    return 2 + 0.5 * additionalHours; 
} 

var fee = calculateFee(5); 

如果使用for循環是一個要求:

function calculateFee(hours) { 
    if (isNaN(hours) || hours <= 0) return 0; 
    var result = 2; 
    if (hours <= 3) return result; 
    var additionalHours = Math.round(hours - 3); 
    for (i = 0; i < additionalHours; i++) { 
     result += 0.5;   
    } 
    return result; 
} 

最後一個例子使用對象:

function FeeCalculator(minimalFee, initialHours, additionalHourFee) { 
    if (isNaN(minimalFee) || minimalFee <= 0) { throw "minimalFee is invalid"; } 
    if (isNaN(initialHours) || initialHours <= 0) { throw "initialHours is invalid"; } 
    if (isNaN(additionalHourFee) || additionalHourFee <= 0) { throw "additionalHourFee is invalid"; } 
    this.minimalFee = minimalFee; 
    this.initialHours = initialHours; 
    this.additionalHourFee = additionalHourFee; 
} 

FeeCalculator.prototype = { 
    calculateFee: function(hours) { 
     if (hours <= this.initialHours) return this.minimalFee; 
     var additionalHours = Math.round(hours - this.initialHours); 
     return this.minimalFee + this.additionalHourFee * additionalHours;   
    } 
}; 

var calculator = new FeeCalculator(2, 3, 0.5); 
var fee = calculator.calculateFee(5); 
0

可能是這樣,抱歉如果它是錯誤的,因爲我沒有測試它。

fee=0 
if (hour>0){ 
    fee=2; 
    hour-=3; 

    //without for loop 
    //if(hour>0)fee+=0.5*hour; 

    //with for loop 
    for(var i=0;i<hour;i++){ 
     fee+=0.5; 
    } 

} 
return fee; 
+0

把它放在do {...} while(0);讓他開心。 – 2009-11-22 10:36:50

+0

是的,思考如何把循環 – YOU 2009-11-22 10:37:10

+0

沒關係,很好的參考 – 2009-11-22 10:38:51