简体   繁体   中英

Javascript: Use a function to change variables to true/false

I'm having trouble using Boolean True/False within my function.

HTML:

<a onclick="selectCategory(animal);">Animal</a>
<a onclick="selectCategory(food);">Food</a>
<a onclick="selectCategory(thing);">Thing</a>

Javascript:

var animal = false;
var food = false;
var thing = false;

function selectCategory(category)
{
     if(category != true)
     {
          category = true;
     }
     else
     {
          category = false;
     }
}

I want this function for example to check if variable "animal" is false , then it should turn to true . If true , then turn to false .

Whenever I try this, it always turn to true , never back to false . The variable category doesn't seem to affect my variables animal , food and thing . It only changes category to true like it's a new variable.

Reassigning a primitive (or any variable at all) won't do anything, by itself, in 99% of situations. Use an object containing boolean values instead, pass the property name, and reassign the property on the object:

 const obj = { animal: false, food: false, thing: false }; function selectCategory(category){ obj[category] = !obj[category]; console.log(obj); }
 <a onclick="selectCategory('animal');">Animal</a> <a onclick="selectCategory('food');">Food</a> <a onclick="selectCategory('thing');">Thing</a>

You definitely have to return in this case as the changes you make are just local to the function scope. But my approach will be a better way to use a small change by using objects:

 var myConfig = { animal: false, food: false, thing: false }; function selectCategory(which) { myConfig[which] = !myConfig[which]; console.log(myConfig); }
 <a href="#" onclick="selectCategory('animal'); return false;">Animal</a> <a href="#" onclick="selectCategory('food'); return false;">Food</a> <a href="#" onclick="selectCategory('thing'); return false;">Thing</a>

Few points to remember:

  • Using an object will not pollute the global scope.
  • You cannot pass variables as parameters, where you want to change the original one. It's pass by value and not reference.
  • Use return false and give href for compatibility.
  • Use myVar = !myVar to toggle boolean.

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