[英]Combining conditional statements in JavaScript
I have two variables that hold objects: 我有两个保存对象的变量:
var person1 = {
name: "Joe",
study: false
};
var person2 = {
name: "Tom",
study: true
};
I've created two functions such that after a function is called, it will call both of these functions: 我创建了两个函数,以便在调用一个函数之后,它将调用这两个函数:
var person1study = function() {
if (person1.study === true){
person.study = false;
}
else {
person1.study = true;
}
};
var person2study = function() {
if (person2.study === true){
person2.study = false;
}
else {
person2.study = true;
}
};
Is there a way that I can combine these who functions into a single function that does that same thing? 有没有一种方法可以将这些功能合并为一个功能相同的功能?
Just declare the object as a parameter: 只需将对象声明为参数即可:
function toggleStudy(person) {
person.study = !person.study;
}
toggleStudy(person1); // invert the "study" flag on the "person1" object
The !
!
operator evaluates its operand as a boolean value, and returns the opposite value. 运算符将其操作数评估为布尔值,然后返回相反的值。
var personStudy = function(person) {
person.study = !person.study;
};
like this? 像这样?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.