gpt4 book ai didi

JavaScript 函数 "X - Y = Z"返回 Y 作为 Z 值

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:09 26 4
gpt4 key购买 nike

我正在尝试对 JavaScript 中的选择应用折扣,但出于某种原因,我的代码返回要减去的总价作为总价:

  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”而不是“total”)

我是否遗漏了什么,或者遗漏了什么?我没有用 JavaScript 做过很多数学运算,所以有点头疼!

非常感谢

最佳答案

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

您想获得折扣后的金额。

你正在这样做:

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);

关于JavaScript 函数 "X - Y = Z"返回 Y 作为 Z 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38686561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com