简体   繁体   中英

javascript function scope challenge

I got stuck at a problem in JavaScript which uses the concept of function scope. Particularly, this is what I need to solve:

Define a function named callFunc that takes one argument, a function f. It should return an array containing the values f(0), f(0), f(1), f(1). You can only call f twice.

My code so far is:

var f = function(x) {
    return x+2;
};

var callFunc = function (f) {
    return [f(0), f(1)];
};

I don't know how I can return an array of four elements using only two calls and the JavaScript function scope principles.

It's really quite simple:

function callFunc(f) {
    var f0, f1;
    f0 = f(0);
    f1 = f(1);
    return [f0,f0,f1,f1];
}

I'm... not entirely sure why you'd have trouble with that. Reducing the number of function calls is something you should be doing anyway (and it's why I cringe at most jQuery code that has $(this) in it like 20 times...)

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