2016-07-31 160 views
2

我试图对JavaScript中的选区应用折扣,但由于某种原因,我的代码返回的总数要减去总价格:JavaScript函数“X-Y = Z”返回Y作为Z值

selectone = parseInt(selectone); 

    var textarea = document.getElementById('discount'); 
    var word = '15off'; 
    var textValue=textarea.value; 
    if (textValue.indexOf(word)!=-1) 
    { 
     var discval = parseFloat(selectone); 
     var num = parseInt(discval); 
     var retval = num - (num * .15); 

    } else { 
     var retval = 0 
    } 

    var total = selectone - retval; 
    document.getElementById("rettotal").innerHTML = "Price starts from £" + total; 
} 

例如,如果某物费100£和15%的折扣被施加,总将 '15£' 而不是 '£100'( 'RETVAL' 而不是 '总')

我在这里错过了什么,或者有什么遗漏? 我还没有在JavaScript中做过数学,所以有点过头了!

非常感谢

+0

什么是selectOne变量? – TheValyreanGroup

+1

z = x -y;可能会工作 –

+0

@RonRoyston joker(; – num8er

回答

2

因为......数学。

selectone = parseInt(selectone); 
...  
var discval = parseFloat(selectone); // doesn't change the things, it's an int already 
var num = parseInt(discval); // so num is essentially discval, which is selectone 
var retval = num - (num * .15); // here you get 85% of num... 
... 
var total = selectone - retval; // here you get 15% back 

解决方法是从retval删除num -,从而var retval = num * .15;

还有你的代码可以被压缩到这一点:

var textarea = document.getElementById('discount'); 
var total = parseFloat(selectone)*(1-0.15*textarea.value.includes("15off")); 
document.getElementById("rettotal").innerHTML = "Price starts from £" + total; 

或者,如果你有includes()问题不支持你的浏览器(如果它是IE),你也可以使用match()

var total = parseFloat(selectone)*(1-0.15*(textarea.value.match("15off")|0)); 
+0

你毁了计算!!只需返回(总价 - 15%)!!!看到其他答案! –

+1

@Ismail我没有毁了任何东西。*只需返回(总价 - 15% )* - 这就是我想要做的,rea d最后一句话。另一个答案基本上提到了和我一样的东西。 – nicael

+0

我相信OP会在你的代码后头痛:D无论如何,答案是正确的! –

3

你在逻辑问题的数学部分。

您想要折扣后获得金额。

你这样做:

var retval = num - (num * .15); // 100 - (100 * .15) = 85 

,但你从量消除折后:

var total = selectone - retval; // 100 - 85 = 15 


因此,这里的修复:

var price = parseFloat(selectone); 
var discount = (textValue.indexOf('15off') != -1)? 
       price * .15 
       : 0; 
var total = price - discount; // 100 - 15 = 85 

或者只是简单的(如果折扣适用一次):

var total = parseFloat(selectone); 
if(textValue.indexOf('15off') != -1) { 
    total *= .85; 
} 

让我们灵活(应用多种折扣价):

var textValue = 'take this 15off and this 10off'; 
 
    var price = parseFloat(1000); 
 
    var total = price; 
 

 
     total-= (textValue.indexOf('15off') != -1)? 
 
        price * .15 
 
        : 0; 
 

 
    console.log(total); 
 

 
     total-= (textValue.indexOf('10off') != -1)? 
 
        price * .15 
 
        : 0; 
 

 
    console.log(total);

+1

谢谢你num8er。你的答案已经过了我的头,但我肯定明天在睡觉后看它,我会得到它;) 非常感谢对过程的解释 - 非常感谢 – Aaron

0

你有一个JavaScript运算符优先级和有意味的问题。这是你的部分语法错误。 在这样的表达式:

x - y = z 

您认为:

 z = x - y //but it's not. 

你真正想说的是:

 y = z and x = x - z 
相关问题