简体   繁体   中英

JavaScript global add function

var num;

function newNum(num) {
    num += 1;
    return num;
}

So I am trying to make a new function in google sheets in which newNum() will take any number and add it to the previous (global) num.

ie newNum(1) will print 2 .
newNum(5) will now print 7 .
newNum(3) will now print 10 and so on.

Thank you everyone in advance!

If you want it to add to a global total each time you call, then you have to give your global variable and your function argument different names so each can be accessed an dyou also need to initialize the global to your desired initial value.

 var num = 1; function newNum(add) { num += add; return num; } log(newNum(1)); log(newNum(5)); log(newNum(3)); // log output in the snippet function log(x) { var div = document.createElement("div"); div.innerHTML = x; document.body.appendChild(div); } 

To encapsulate the total a little better and keep from exposing it as a public global, you could also do it this way:

 var newNum = (function() { var num = 1; return function(add) { num += add; return num; } })(); log(newNum(1)); log(newNum(5)); log(newNum(3)); // log output in the snippet function log(x) { var div = document.createElement("div"); div.innerHTML = x; document.body.appendChild(div); } 

I don't know about Google Sheets, but the usual way to do this in plain JS is to use a function that itself returns a function that is "closed over" the variable that holds the total, without making that total visible as a global variable:

function makeAccumulator() {
    var total = 0;
    return function(n) {
        total += n;
        return total;
    }
}

var newNum = makeAccumulator();

With this you can make multiple accumulators, each of which will keep track of their own total:

var newNum2 = makeAccumulator();

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