【发布时间】:2020-10-19 16:31:33
【问题描述】:
我有一个任务要求以下内容: “本田-丰田汽车保险:
编写一个 JavaScript 程序,根据以下规则打印为车辆支付的保险费:
一辆全轮驱动的本田售价 450 美元。
两轮驱动的本田售价 350 美元。
一辆全轮驱动的丰田汽车售价 300 美元。
一辆两轮驱动的丰田汽车售价 250 美元。
任何其他类型的车辆都会生成错误消息。该网页应提示用户提供适当的信息:询问汽车型号(本田或丰田),然后是否是全轮驱动,然后显示保险费。 打印保险费后,程序应询问用户是否要使用重复结构“为另一辆车投保”
我之前没有任何使用循环的经验,并且无法弄清楚如何让程序在提示“您要为另一辆车投保吗?”时回答“是”后循环回到开头。这是我使用的代码:
function feeCalc() //Linked to button on html page. Perhaps this was the issue?
{
let carType = prompt('Do you have a Honda or Toyota?');
//changes case of input string to lowercase
let carTypeLC = carType.toLowerCase();
//prices of different insurance
let hondaAWD = "450.00";
let honda2WD = "350.00";
let toyotaAWD = "300.00";
let toyota2WD = "250.00";
if ((carTypeLC == 'honda') || (carTypeLC == 'toyota')) {
let wheelDrive = prompt('Does your vehicle have All Wheel Drive or Two Wheel Drive? Enter \"AWD\" or \"2WD\".');
//changes case of input string to lowercase
let wheelDriveLC = wheelDrive.toLowerCase();
if ((carTypeLC == 'honda') && (wheelDriveLC == 'awd')) {
alert('The insurance fee for your Honda AWD is $' + hondaAWD);
document.getElementById("webDisplay").innerHTML = 'The insurance fee for your Honda AWD is $' + hondaAWD;
} else if ((carTypeLC == 'honda') && (wheelDriveLC == '2wd')) {
alert('The insurance fee for your Honda 2WD is $' + honda2WD);
document.getElementById("webDisplay").innerHTML = 'The insurance fee for your Honda 2WD is $' + honda2WD;
} else if ((carType = 'toyota') && (wheelDrive == 'awd')) {
alert('The insurance fee for your Toyota AWD is $' + toyotaAWD);
document.getElementById("webDisplay").innerHTML = 'The insurance fee for your Toyota AWD is $' + toyotaAWD;
} else if ((carType = 'toyota') && (wheelDrive == '2wd')) {
alert('The insurance fee for your Toyota 2WD is $' + toyota2WD);
document.getElementById("webDisplay").innerHTML = 'The insurance fee for your Toyota 2WD is $' + toyota2WD;
} else {
alert('There seems to be an error. Please try again.');
}
} else {
alert('There seems to be an error. Please try again.');
}
let restart = prompt('Do you want to insure another vehicle? \"y\" or \"n\"')
}
do {
feeCalc
} while (restart = 'y' && restart != 'n');
//I commented the above do while loop code out because it was not working and made the rest of my code not function. I had to submit the assignment so I submitted what was working.
该函数链接到 html 页面上的一个按钮,这可能是我的问题,但我没有时间在截止日期前及时编辑我刚刚构建的所有代码。我很确定我需要使用 do while 循环,但我根本无法让它工作(因此我将它注释掉了)。我是初学者并正在参加在线课程,所以我正在尽我所能提供给我的信息,但不幸的是,教授没有发布任何关于如何使用数值之外的任何内容进行循环的示例。除了循环部分之外,上面的代码工作正常。请帮忙,因为我的教授评分很慢,也没有提供具体的反馈。
【问题讨论】:
-
您有很多使用单等号的条件检查。这仅用于分配。
-
为了澄清上面的评论,你有
else if ((carType='toyota') ...,但你应该使用==,所以else if ((carType == 'toyota') ...。这也存在于另一个地方else if ((carType='toyota') ...。这会破坏您的流程/逻辑,因此请先修复此错误,然后再解决循环问题。 -
@James 谢谢,我已经编辑了代码以确保我的条件检查有两个 == 。
-
@WOUNDEDStevenJones 感谢您的解释,这很有帮助!
-
还有一个 -
while (restart = 'y' ...
标签: javascript function loops do-while