简体   繁体   中英

Apparently simple function not returning anything

I'm sure I'm just having a moment, but I can't figure this out for anything. I wanted to create a quick function to sum up a particular JSON object's values over an array, but it returns nothing. Here's the code:

var a=[{"b":"23"},{"b":"37"}]
function sumJSON(json,elem){
    var total=0;
    $.each(json,function(index,item){
        var count=index+1;
        total+=Number(item[elem]);
        if(count===json.length){
            return total;
        }
    })
}
console.log(sumJSON(a,"b"));

Here's the jsfiddle

Just in case you want this to be solved with plain javascript.

 var a = [{"b":"23"},{"b":"37"}] function sumJSON(a,key) { return a.reduce((s, data) => s + (+data[key]), 0) } console.log(sumJSON(a, 'b')) 

var a=[{"b":"23"},{"b":"37"}]
function sumJSON(json,elem){
    var total=0;
    $.each(json,function(index,item){
        total+=Number(item[elem]);
    })
    return total;
}
console.log(sumJSON(a,"b"));

$each needs not to return anything, just calls a function for each member of the collection, you need to return the total after the call to $.each, once the function has been called for all the elements

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