简体   繁体   English

在javascript函数中切换传入变量布尔值

[英]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. 我的示例在下面,但是由于语句“ item”的第一部分未分配给传入的变量,因此此方法不起作用。

let editable = true;

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

toggleEditMode(editable);

Any help? 有什么帮助吗?

You have to learn how js passes function arguments. 您必须学习js如何传递函数参数。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM