最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Correct way to toggle between two string values with ternary expression - Stack Overflow

programmeradmin5浏览0评论

I am trying to have a string that toggle between two values. I have declared as ternary

public position: string = (this.position == "positionOne" ? "positionOne" : "positionTwo");

What I would like to have a function for directly toggle from "positionOne" to "positionTwo" (value of the string). Something like `

togglePosition = function() 
     {this.position = !this.position}

and then it takes the opposite string as value. Or I need to do the plete evaluation also if declared as ternary? and then see if (position = "positionOne")... do whatever.. or else the upside down. You know what I mean? :) What solution you suggest to me?

Thanks a lot from now

I am trying to have a string that toggle between two values. I have declared as ternary

public position: string = (this.position == "positionOne" ? "positionOne" : "positionTwo");

What I would like to have a function for directly toggle from "positionOne" to "positionTwo" (value of the string). Something like `

togglePosition = function() 
     {this.position = !this.position}

and then it takes the opposite string as value. Or I need to do the plete evaluation also if declared as ternary? and then see if (position = "positionOne")... do whatever.. or else the upside down. You know what I mean? :) What solution you suggest to me?

Thanks a lot from now

Share Improve this question edited Apr 8, 2017 at 19:16 Sam asked Apr 8, 2017 at 19:14 SamSam 1,4792 gold badges20 silver badges34 bronze badges 3
  • 2 do you really mean javascript? or java? if javascript, why do you use a typed variable? – Nina Scholz Commented Apr 8, 2017 at 19:15
  • 1 @NinaScholz it's typescript – vol7ron Commented Apr 8, 2017 at 19:19
  • 3 Your ternary operation is fine, except that you should swap the final two values, otherwise you don't change anything. – trincot Commented Apr 8, 2017 at 19:20
Add a ment  | 

5 Answers 5

Reset to default 8

You could use an object and the keys as the wanted value.

function toggle(v) {
    return { positionOne: 'positionTwo', positionTwo: 'positionOne' }[v];
}
 
var position = 'positionOne';
console.log(position);
position = toggle(position);
console.log(position);
position = toggle(position);
console.log(position);

As an alternative you could use this (in cases where the values do not match "half-way"):

function toggle(pos) {
    return 'positionOnepositionTwo'.replace(pos, '');
}

pos = 'positionOne';
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));

Alternative with find

function toggle(pos) {
    return ['positionOne','positionTwo'].find(x => x !== pos);
}

pos = 'positionOne';
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));
console.log(pos = toggle(pos));

Of course, you could use Array.find to do the same thing Nina mentioned:

var log = console.log;
function toggle(v) {
   return ['positionOne','positionTwo'].find(s=>s!=v);
}
 
var position = 'positionOne';
log( position );

position = toggle(position);
log( position );

position = toggle(position);
log( position );

I think that the 'correct way' will depend on the person and project. For simple problems i prefer the ternary way or the answer by @Nina Scholz.

You can also use ES6 destructuring:

({ [position]: position } = { positionOne: "positionTwo", positionTwo: "positionOne" });

<!DOCTYPE html>
<html>

<body>

  <button onclick="myFunction()">Click me</button>

  <p id="demo"></p>

  <script>
    var position = "positionOne";

    function myFunction() {
      ({
        [position]: position
      } = {
        positionOne: "positionTwo",
        positionTwo: "positionOne"
      });
      document.getElementById("demo").innerHTML = position;
    }
  </script>

</body>

</html>

An interesting alternative using destructuring, although probably not the best for this use case, can be obtained by toggling the values of two variables:

var positionA = "positionOne";
var positionB = "positionTwo";
[positionA, positionB] = [positionB, positionA];

<!DOCTYPE html>
<html>

<body>

  <button onclick="myFunction()">Click me</button>

  <p id="demo"></p>

  <script>
    var positionA = "positionOne";
    var positionB = "positionTwo";

    function myFunction() {
      [positionA, positionB] = [positionB, positionA];
      document.getElementById("demo").innerHTML = positionA;
    }
  </script>

</body>

</html>

Or just use an object:

var position = {a: 'positionOne', b: 'positionTwo'};    
[position.a, position.b] = [position.b, position.a];

The advantage of this solution is that enable one to change between multiple values and not just two (However for this you should probably use the solution mentioned earlier in its extensive form).

<!DOCTYPE html>
<html>

<body>

  <button onclick="myFunction()">Click me</button>

  <p id="demo"></p>

  <script>
    var positionA = "positionOne";
    var positionB = "positionTwo";
    var positionC = "positionThree";
    var positionD = "positionFour";

    function myFunction() {
      [positionA, positionB, positionC, positionD] = [positionB, positionC, positionD, positionA];
      document.getElementById("demo").innerHTML = positionA;
    }
  </script>

</body>

</html>

It might make more sense to store the state of which string to display in a boolean variable, which you can easily toggle, then write a method that returns the appropriate string based on the boolean variable.

发布评论

评论列表(0)

  1. 暂无评论