2017-10-09 184 views
-1

我想要使用JavaScript來計算某個東西的價格,具體取決於輸入的內容。默認價格是1000英鎊,但如果數量超過5.5,價格每增加0.1英鎊250英鎊,直到總價格達到50,000英鎊。我將會採用if語句,但在這種情況下,這是不可行的。有沒有辦法做到這一點使用for循環?根據輸入的內容計算出價格的Javascript計算

+0

聽起來像是一門功課的問題。 – jeff

+2

發佈一些你已經試過的代碼。然後有人會幫你糾正這一點。 –

回答

0

你只是在兩個選擇拆分它,沒必要爲一個循環營造的情況:

// Option 1 is the easiest, the 'normal/default price" 
const thresholdQuantity = 5.5; 
let price = 1000; // we set the base value 

// Option 2: Only do extra work when you are past the threshold: 
if(quantity > thresholdQuantity){ 
    // Now we want to know how many steps we differ from 5.5 
    let diff = Math.floor((quantity - thresholdQuantity))*10; 
    price += diff*250; 
    // And now make sure we dont go too high: 
    price = Math.min(50000, price); 
} 
+0

這將返回50000.例如,如果我將數量設置爲6我應該得到2250作爲價格,但我得到50000 – AndyS54M3

+0

將最大值更改爲最小值,是一個錯誤(您可能已經發現自己;)50000只出現一次代碼) – Martijn

+0

準確的公式可以改變,如果你想要稍微不同的東西,這是我顯示的原則 – Martijn