您在 for 循环var
之前缺少一个关键字。i
没有它将i
成为一个全局变量。此外,使用数组文字符号 ( []
) 比 write 更短/更快/更清晰,new Array()
如下所示:myArray = []
只是一个一般提示......还要注意,for (var ... in ...)
它用于遍历对象的成员,通常不循环遍历数组。
如果您稍后在脚本中不使用myBooks
andmyPrices
数组中的值,那么您在这里不需要任何数组 - 您可以组合两个循环并将提示返回的值保存在循环内的临时变量中。见下文:
function enterFood()
{
var total_cost = 0;
for (var i = 1; i <= 5; i++)
{
var name = prompt("Enter name of Food","");
var cost = parseFloat(prompt("Enter cost of food",""));
document.getElementById("cost").innerHTML += i + ". " + name + ". Cost: £" + cost + "<br />";
total_cost += cost;
}
document.getElementById("total_cost").innerHTML = total_cost;
}
此外,仅查看您的代码有一些评论:
1) for 循环内部之前缺少var
关键字。i
没有它,我将成为一个全球变量。
2)在 Javascript 中,数组是一个对象,它具有各种作为函数的属性。使用数组文字表示法(即[]
)比编写new Array
..例如更干净/更短和更快myArray = []
3) The For-In loop is used to iterate through the members of an object and generally NOT to loop through an array. For-In loops are slower than normal loops. You want to use a regular loop for iterating over an array.
4) If you are not using the values in the myBooks
and myPrices
arrays later on in your script then you do not need any arrays here, you could just combine your 2 loops and save the values returned from the prompts inside temporary variables inside the loop.
EDIT: As corrected by @Teemu, i
is hoisted from for..in
loop so will not become global.