[英]How do I get the calculation of the sum of the items in an array with a for loop?
所以我對此有點迷茫,所以我所做的是創建顯示其索引的 for 循環,例如:0 1 2 3 4 5 6 7 8 9。
let tasks =["swim", "study", "eat", "break", "sleep", "Cook", "Clean", "watch TV", "Train", "Code"]
let x;
for(x of tasks)
{
document.getElementById("answers").innerHTML += x + " ";
console.log(x);
}
所以上面的代碼我使用了 for of 循環來獲取每個項目的索引。 我想做的是如何將每個索引相互添加,所以它應該是 1 + 2 + 3 ...等等。
//Activity 2 - Edit the loop created above, to now calculate the sum of all the items leading up to 10. e.g. 1 + 2 + 3 = 6
//console.log your output
//Add your code below
let index;
let sum;
for(x = 0; x < tasks.length; x++)
{
index = document.getElementById("sumOftasks").innerHTML += x + " ";
}
你的代碼將返回數組的值,當你對它求和時它會給你結果 NaN
您可以從數組中獲取值,查找索引並將其求和。
for(x of tasks)
{
let index = tasks.indexOf(x);
document.getElementById("answers").innerHTML += index + " ";
}
我會幫你的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.