这个想法是生成一个从1到10的随机数,这将是订购产品的磅数。然后,使用该数字,代码将计算产品的成本和运输成本,将它们相加以创建总计。然后,它会将有关购买的信息写入HTML文档。
问题不是随机数发生器;这工作正常。它似乎也不是将信息写入文档的最后一步。相反,我的计算似乎包含在if-else语句中,不起作用。 JavaScript正在将costBox
,costShipping
和costTotal
视为未定义。我已经尝试改变语法,并且我已经检查了代码以确保没有丢失的括号或括号。我已经查阅了我的教科书,但代码的布局类似。你能帮我弄清楚出了什么问题吗?
这是我的代码:
var num = Math.ceil(Math.random() * 10);
var costBox;
var costShipping;
var costTotal;
if (num >= 1 && num <= 5) {
costBox == 20;
}
else if (num >= 6 && num <= 9) {
costBox == 15;
}
else if (num == 10) {
costBox == 10;
}
if (num >= 1 && num <= 3) {
costShipping == 5;
}
else if (num >= 4 && num <= 7) {
costShipping == 10;
}
else if (num == 8 || num == 9) {
costShipping == 15;
}
else if (num == 10) {
costShipping == 20;
}
costBox == costBox * num;
costTotal == costBox + costShipping;
window.onload = function() {
document.getElementById("pageNum").innerHTML = num;
document.getElementById("pageBox").innerHTML = costBox.toFixed(2);
document.getElementById("pageShipping").innerHTML = costShipping.toFixed(2);
document.getElementById("pageTotal").innerHTML = costTotal.toFixed(2);
}
以下是NPE建议之后的代码:
var num = Math.ceil(Math.random() * 10);
var costBox;
var costShipping;
var costTotal;
if (num >= 1 && num <= 5) {
costBox = 20;
}
else if (num >= 6 && num <= 9) {
costBox = 15;
}
else if (num == 10) {
costBox = 10;
}
if (num >= 1 && num <= 3) {
costShipping = 5;
}
else if (num >= 4 && num <= 7) {
costShipping = 10;
}
else if (num = 8 || num = 9) {
costShipping = 15;
}
else if (num = 10) {
costShipping = 20;
}
costBox == costBox * num;
costTotal == costBox + costShipping;
window.onload = function() {
document.getElementById("pageNum").innerHTML = num;
document.getElementById("pageBox").innerHTML = costBox.toFixed(2);
document.getElementById("pageShipping").innerHTML = costShipping.toFixed(2);
document.getElementById("pageTotal").innerHTML = costTotal.toFixed(2);
}
答案 0 :(得分:4)
以下是比较,而非作业:
costBox == 20;
将==
更改为=
(此处以及所有其他类似地点)。
另请注意,Math.random()
可以准确返回0
,而您的代码不会处理该问题。