簡體   English   中英

嘗試使用循環查找數組的總和和平均值

[英]Trying to find the sum and the average of an array using loop

“價格”是一個包含 6 個價格的數組。 我想在該數組中找到總和和平均值以及最高價和最低價。 目前我的 answer2 只在一條直線上顯示數字。

    let answer2 = ""

    for (let k=0; k < price.length; k++) {
        answer2 += price[k];

    }```

您始終可以利用 EcmaScript 的 Arrays reduce 方法,在您的案例中使用該方法查看這段代碼。 希望這對朋友有幫助,干杯!

// The array with the prices you mentioned but didn't include on the code
const price = [23,45,12,67,89,87];
// Let's calculate the sum of all array elements first
const sum = price.reduce((acc,i)=>acc+i,0);

// we print this and use the array length property to calculate average
console.log(`Sum: ${sum} Average: ${(sum/price.length).toFixed(2)}`);

您可以創建一個簡單的 for 循環以從數組中獲取(Sum、Avg、Max 和 Min)

let price=[23,88,45,66,3,10,2];
let result={"sum":0,"avg":0,"max":0,"min":0}
let size = price.length;
for(let i=0;i<size;i++){
    if(price[i]>result.max){
        result.max=price[i];
    }
    if(i==0 || price[i]<result.min){
        result.min=price[i]
    }
    result.sum+=price[i]
}
result.avg=Number((result.sum/size).toFixed(2));
console.log(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM