2017-10-09 118 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