[英]JavaScript, Using a for loop to calculate the sum of all the values within an array
[英]Calculate sum of array values in Javascript
我試圖在以下代碼中找到玩具的總和。 我的嘗試在那里: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;
您的代碼失敗,因為您的“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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.