gpt4 book ai didi

javascript - 将忽略某些值的逻辑添加到当前函数 "Total"

转载 作者:行者123 更新时间:2023-11-28 14:15:49 28 4
gpt4 key购买 nike

我的项目要插入几个小时,你花了多少时间。它适用于整数值,但现在我需要添加字符串值。像Sunday ="NotWorknig"这样的东西;星期一=“8”;星期二=“生病了”;

function TotalP1() {
var text1_p1 = 0;
var text2_p1 = 0;
var text3_p1 = 0;
var TotalAmount = 0;

text1_p1 = $("#text1_p1").val() == '' ? 0 : $("#text1_p1").val();
text2_p1 = $("#text2_p1").val() == '' ? 0 : $("#text2_p1").val();
text3_p1 = $("#text3_p1").val() == '' ? 0 : $("#text3_p1").val();



TotalAmount =
parseInt(text1_p1) +
parseInt(text2_p1) +
parseInt(text3_p1);


$("#texttotal_p1").val(TotalAmount);

}

我想重写函数并使其工作相同,但忽略字符串值或特定整数值,例如“29”将是“假日”,如果用户插入的假日值是 29 但它被函数忽略并且不会影响总和。没有给我“南”值。有什么提示、教程吗?

最佳答案

解决方案 1:

function TotalP1() {
var text1_p1 = 0;
var text2_p1 = 0;
var text3_p1 = 0;
var TotalAmount = 0;

text1_p1 = $("#text1_p1").val() == '' ? 0 : $("#text1_p1").val();
text2_p1 = $("#text2_p1").val() == '' ? 0 : $("#text2_p1").val();
text3_p1 = $("#text3_p1").val() == '' ? 0 : $("#text3_p1").val();

var parsedValueP1 = parseInt(text1_p1);
var parsedValueP2 = parseInt(text2_p1);
var parsedValueP3 = parseInt(text3_p1);

if(!isNaN(parsedValueP1)) {
TotalAmount += parsedValueP1;
}

if(!isNaN(parsedValueP2)) {
TotalAmount += parsedValueP2;
}

if(!isNaN(parsedValueP3)) {
TotalAmount += parsedValueP3;
}

$("#texttotal_p1").val(TotalAmount);

}

解决方案 2:

function TotalP1() {
var text1_p1 = 0;
var text2_p1 = 0;
var text3_p1 = 0;
var TotalAmount = 0;
var numberRegex = /^\d+$/; //Only for Integers

text1_p1 = $("#text1_p1").val() == '' ? 0 : $("#text1_p1").val();
text2_p1 = $("#text2_p1").val() == '' ? 0 : $("#text2_p1").val();
text3_p1 = $("#text3_p1").val() == '' ? 0 : $("#text3_p1").val();

if(numberRegex.test(text1_p1)) {
TotalAmount += parseInt(text1_p1);
}

if(numberRegex.test(text2_p1)) {
TotalAmount += parseInt(text2_p1);
}

if(numberRegex.test(text3_p1)) {
TotalAmount += parseInt(text3_p1);
}

$("#texttotal_p1").val(TotalAmount);

}

关于javascript - 将忽略某些值的逻辑添加到当前函数 "Total",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57509219/

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