how to create array that sums values of another array? (javascript)

时间:2015-05-12 23:12:53

标签: javascript arrays

say I have an array with the following ten values: 329,374,353,336,137,340,374,374,356,329 I want to create a new array which uses those values and creates a sum according to their position, so that the new array (based on those values) would look like so:

329, 329+374, 329+374+353, 329+374+353+336, ... using javascript alone (no jquery) how can I achieve that?

2 个答案:

答案 0 :(得分:4)

You can use ipython notebook and a running total variable:

.map()

Working demo: http://jsfiddle.net/jfriend00/9ekkk1r3/


var array = [329,374,353,336,137,340,374,374,356,329], sum = 0;
var result = array.map(function(item) {
    sum += item;
    return sum;
});
console.log(result);

var array = [329,374,353,336,137,340,374,374,356,329], sum = 0; var result = array.map(function(item) { sum += item; return sum; }); // show results in snippet document.write("[" + result.join(',') + "]"); is useful here because it both iterates through the source array and creates a new result array which is exactly what you want to do. Then, all your have to do to simplify the result is to keep a running total of the sum so far so you know what to add for each new value.

答案 1 :(得分:1)

function getSomeDataFromServer() {

    if (myData) {
        // call to backend was previously made and myData is already loaded 
        return $q.when(myData);
    } else {
        // get data from server
        return $http.get(my_url_endpoint).then(function(response) {
            // cacheResult() will set myData = response.data
            return cacheResult(response);
        });
    }
}