so, i was make a block for my extension which is the “average of array” block but when i tried to add up the sum it returns NaN. Here’s the code:
//% block="Find the average of $array"
export function AverageOf(array: number[]) {
let sum: 0
for (let i = 1; i < array.length; i++) {
sum += array[i];
console.log(sum)
}
return sum;
}
Also there are three other bugs I’m pretty sure in your block:
Missing Division: You are only adding the numbers, not dividing by the array length to get an actual average.
Skipping the First Element: Your loop starts at let i = 1. JavaScript arrays start at 0, so you are completely skipping the first item in the list.
Empty Arrays: If an empty array is passed, dividing by a length of 0 will return NaN. [1]
I fixed your code so it gets the average of an array.
//% block="Find the average of $array"
export function AverageOf(array: number[]): number {
if (array.length === 0) return 0; // Handle empty array case
let sum = 0; // Correctly initializes value to 0
for (let i = 0; i < array.length; i++) { // Starts at index 0
sum += array[i];
}
return sum / array.length; // Correctly calculates the average
}