简体   繁体   中英

toggle passed in variable boolean value in javascript function

I would like to create a re-usable function that changes the boolean value of the variable that is passed in.

My example is below however this doesn't work as the first part of the statement 'item' is not assigned to the variable passed in.

let editable = true;

     function toggleEditMode (item){
            item = !item;
        }

toggleEditMode(editable);

Any help?

You have to learn how js passes function arguments. It is passing by value here. Read this by value vs reference

Basically you can't pass by reference like you are trying to. You can make an object and then change a property on that object inside your function and it will work how you are expecting.

var i = { a:true }

function c(o){
  o.a = !o.a
}

c(i)
console.log(i);

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