最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Simple average function in Javascript - Stack Overflow

programmeradmin0浏览0评论

How could I calculate average using a function:

function calculate(array) {
    var sum = 0;
    for (var i = 0; i < array.length; i++) {
        sum = sum + array[i];
    }
    return sum;
}
document.write(calculate([24, 88, 12, 4]));

(I don't understand how to get the arguments length)

How could I calculate average using a function:

function calculate(array) {
    var sum = 0;
    for (var i = 0; i < array.length; i++) {
        sum = sum + array[i];
    }
    return sum;
}
document.write(calculate([24, 88, 12, 4]));

(I don't understand how to get the arguments length)

Share Improve this question edited Dec 17, 2016 at 16:06 jophab 5,50914 gold badges44 silver badges61 bronze badges asked Dec 17, 2016 at 14:14 U.P.U.P. 811 gold badge1 silver badge6 bronze badges 2
  • 7 Just return sum / array.length;? – Sebastian Simon Commented Dec 17, 2016 at 14:15
  • array.size() & array.length both have your argument length – AmiNadimi Commented Dec 17, 2016 at 14:21
Add a comment  | 

7 Answers 7

Reset to default 11

To get the average, just sum the values and divide by number of indices in the array, i.e. the length

function calculate(array) {
    return array.reduce((a, b) => a + b) / array.length;
}

console.log(calculate([24, 88, 12, 4]));

You can calculate the average easily with reduce() method:

const avg = array.reduce((a, b) => a + b) / array.length

Use the array's length property:

function calculate(array) {
    var i = 0, sum = 0, len = array.length;
    while (i < len) {
        sum = sum + array[i++];
    }
    return sum / len;
}

Your function sum all the number in the array. in the return line you should change to something like this:

return sum / array.length;

And you should change this line:

console.log(calculate([24, 88, 12, 4]));

to this:

console.log(calculate({24, 88, 12, 4}));

You can try this way as well by using for-of loop.

function average(...nums) {
    let total = 0;
    for(const num of nums) {
    total += num/nums.length;
    }
    return total;
}
console.log(average(24, 88, 12, 4));

This for...of loop should work perfectly

function average(...nums) {
    let sum = 0;
    let avg = 0;

    for(const num of nums) {
    sum += num;
    avg = sum/nums.length;
    }

    return avg;
}
console.log(average(24, 88, 12, 4));

x = []
function average(...x) {
    let sum = 0,
        avg = 0;
    for (let i of x ){
        sum = sum + i;
        avg = sum/x.length;
    }
    
    return avg
}

console.log(average(2, 6 , 8 , 14));

发布评论

评论列表(0)

  1. 暂无评论