计算Javascript中数组值的总和

时间:2018-11-12 09:32:28

标签: javascript arrays object sum

我正尝试在以下代码中找到玩具的总和。我的尝试在那里:calcTotal,但它仅提供NaN的结果。我之前在calcTotal函数中使用了相同的代码来计算数组值的总和,但是由于某种原因,它在这里不起作用,请帮忙吗?该程序的任务是让用户输入狗的名字和玩具数量,将信息放入对象中,然后放入数组中。然后需要显示玩具的总量。先感谢您。

    function init() {
    var dogarray = [];
    var dogobject = {};


    var dogname = prompt("Please enter dog name");
    var toyamt = prompt("Please enter toy amount");
    while (dogname != "" && toyamt != "") {
        dogobject.name = dogname;
        dogobject.toys = toyamt;
        dogarray.push(Object.values(dogobject) + "<br />");
        dogname = prompt("Please enter dog name");
        toyamt = prompt("Please enter toys amount");

    calcTotal(dogarray);
}

}

function calcTotal(dogarray) {
    var sum=0;
    var i;

    for(i=0; i<dogarray.length; i++){
        sum = sum + dogarray[i].toys;       
    }

    document.getElementById("msg3").innerHTML = "Total number of toys: " + sum;

}

window.onload = init; 

1 个答案:

答案 0 :(得分:0)

您的代码失败,因为您的“ dogarray”被填充为String类型的值,并且字符串没有“ toy”属性。发生这种情况是由于Object.values(dogobject) + "<br />"Object.values返回一个字符串数组,当与"<br />"连接时,将转换为单个字符串。

下面是一些工作代码:

function init() {
    var dogarray = [];
    var dogname = prompt("Please enter dog name");
    var toyamt = prompt("Please enter toy amount");
    while (dogname != "" && toyamt != "") {
        dogarray.push({ // just store raw objects
            name: dogname,
            toys: Number(toyamt) // cast to number
        });
        dogname = prompt("Please enter dog name");
        toyamt = prompt("Please enter toys amount");

        calcTotal(dogarray); // maybe move this out of the while loop?
    }
    renderAll(dogarray); // render dog names and toys
}

function renderAll(dogarray) {
    var vHtml = 'Dogs & Toys:<br />';
    var i;

    for (i = 0; i < dogarray.length; i++) {
        vHtml = vHtml + dogarray[i].name + ', ' + dogarray[i].toys + '<br />';
    }

    document.getElementById('msg1').innerHTML = vHtml;
}

function calcTotal(dogarray) {
    var sum=0;
    var i;

    for(i=0; i<dogarray.length; i++){
        sum = sum + dogarray[i].toys;       
    }

    document.getElementById('msg3').innerHTML = "Total number of toys: " + sum;
}

window.onload = init;