简体   繁体   中英

To set and return a variable value without creating an additional variable

Is it possible to compact the function below so there is no variable created?

    var flag=true;
    //...
    my.flagValue=function(){
        var f=flag;
        flag=false;
        return(f);
    };

Basically, to set and return (the previous) value at the same time.

Well, normally there's no way to return something before setting it. But in this specific case, you can use some magic to pull it off. Though your original code is far more readable and maintainable:

my.flagValue = function () {
    return (flag && !(flag = false));
};

If flag is true, then it will perform like this:

return (true && !(flag = false)); //!(flag = false) is true, so true is returned.

If flag is false, then it will perform like this:

return (false && !(flag = false)); //obviously returns false.

Though, I really do encourage you not to do this. It's obscure and requires a bit of logic parsing to sort out. I just wanted to demonstrate that it's possible to do what you're looking to do in this specific case.

If you are just flipping the value of flag between true and false then this might work for you:

my.flagValue=function(){
    return !(flag = newValue);
};

This will set flag to newValue and return opposite value from the function.

You can try this as well, If I understood the question correctly :)

   my.flagValue=function(){
             return flag ? !flag : flag ;
          };

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