1

我有以下 Javascript。我正在尝试使用“for in”来计算 myCosts 数组值的总和;循环然后将它们显示在页面上。我想我快到了。

function enterFood() 
{ 
    var myFoods = new Array() 
    var myCosts = new Array() 

    for (i = 1; i <= 5; i++) 
    { 
        myFoods[i] = prompt("Enter name of Food",""); 
        myCosts[i] = parseFloat(prompt("Enter cost of food","")); 
        document.getElementById("cost").innerHTML += i + ". " + myFoods[i] + ". Cost: £" + myCosts[i] + "<br />"; 
    } 

    for (var i in myCosts) 
    { 
        document.getElementById("total_cost").innerHTML =+ i; 
    } 
}  

任何人都可以提供任何帮助以便我完成这个吗?

4

2 回答 2

2

您应该正确地迭代数组:

var totalElement = document.getElementById("total_cost"),
    total_cost = parseFloat(totalElement.innerHTML);

for (var i = 0, len < myCosts.length; i < len; i++) {
    total_cost += myCosts[i];
}

totalElement.innerHTML = total_cost;
于 2013-02-11T12:47:23.893 回答
2

您在 for 循环var之前缺少一个关键字。i没有它将i成为一个全局变量。此外,使用数组文字符号 ( []) 比 write 更短/更快/更清晰,new Array()如下所示:myArray = []只是一个一般提示......还要注意,for (var ... in ...)它用于遍历对象的成员,通常不循环遍历数组。

如果您稍后在脚本中不使用myBooksandmyPrices数组中的值,那么您在这里不需要任何数组 - 您可以组合两个循环并将提示返回的值保存在循环内的临时变量中。见下文:

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.

于 2013-02-11T12:47:57.277 回答