简体   繁体   中英

How do you get js to find the sum of random numbers in this array?

This is a code that creates a random array and tells you which number in that array is the biggest:

var game = function fucntion(length, limit) {
    length = length ? length : 10;
    limit = limit ? limit : 1000;
    var arr = [];
    var max = -1;
    for (var i = 0; i < length; i++) {
        var r = Math.ceil(Math.random() * limit);
        if (r > max) max = r;
        arr.push(r);
    }
    return 'The biggest number in the array: ' + JSON.stringify(arr) + ' is ' + max + '-'; 
};

How do I make JS add up all the numbers in the array and tell me the sum?

Thanks in advance!

You could use reduce like so :

sum = array.reduce(function(a, b) { return a + b; }, 0);

This method explores the array from left to right, taking two elements and reducing them to one element using the provided callback, over and over again, until the end of the array is reached

PS : Try better formatting your post, and do some online research before posting a question. I found out the solution only by typing "js sum array" on internet.

var game = function fucntion(length, limit) {
    length = length ? length : 10;
    limit = limit ? limit : 1000;
    var arr = [];
    var max = -1;
    var sum = 0;
    for (var i = 0; i < length; i++) {
        var r = Math.ceil(Math.random() * limit);
        if (r > max)
            max = r;
        sum = sum + r;
        arr.push(r);
    }
    return 'The biggest number in the array: ' + JSON.stringify(arr) + ' is ' + max + ' and the sum is: ' + sum; 
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM