I can't explain it much in the title but I'm now stuck with having to test 2 variables for the same value and was wondering is there a way to do something like this.
var a = 'abc';
var b = 'def';
if (a=='abc' || b=='abc'){ c = 'z'; }
Now c is the variable that was tested true, so by assigning a value to c it would assign the value to the variable that tested true in the if statement. a and b can have different values but both can have the same value aswell.
CodePudding user response:
No, the expression just yields a result value, with no information stored about which subexpression was truthy. (And separately, JavaScript doesn't have references to variables [at least, not that you can use in your code].) You'll have to break it out into two ifs:
if (a === "abc") {
a = "z";
} else if (b === "abc") {
b = "z";
}
It would be possible to do something like this if the variables were accessor properties (or other function calls) with side effects (since the right-hand operand of the || won't be evaluated at all if the left-hand operand evaluates to a truthy value). Or if they were properties in an object and you tested an array of property names, etc. But it would be unnecessarily complicated. :-)
CodePudding user response:
You could take a switch statement, here you can check various variables agains a certain value.
switch ('abc') {
case a:
a = 'z';
break;
case b:
b = 'z';
break;
}
