Assign only if condition is true in ternary operator in JavaScript

后端 未结 9 1812
小鲜肉
小鲜肉 2020-12-02 22:08

Is it possible to do something like this in JavaScript?

max = (max < b) ? b;

In other words, assign value only if the condition is true.

相关标签:
9条回答
  • 2020-12-02 22:36

    There was no example of ES6, we can use in this way:

    let list = [{id: "abc", name: "test1"}, {id: "xyz", name: "test2"}]
    let selectedData = {};
          list.some((exp) => {
            return (
              exp.id == "xyz" &&
              ((selectedData = exp), true)
            );
          })
    console.log(selectedData);
    
    0 讨论(0)
  • 2020-12-02 22:38

    I think a better approach could be

    max = Math.max(max, b)
    
    0 讨论(0)
  • 2020-12-02 22:45

    There isn't a specific operator that isn't the ternary operator, but you can use it like this:

    max = (max < b) ? b : max;
    
    0 讨论(0)
  • 2020-12-02 22:47

    I think ternary is more suitable try this

    (max < b) ? max = b : '';
    
    0 讨论(0)
  • 2020-12-02 22:49

    you can try:

    (max < b) && (max = b);
    

    look at this example:

    let max = 10;
    let b = 15;
    (max < b) && (max = b)// this will be true
    console.log("max=", max);
    
    let maxx = 10
    let bb = 5;
    (maxx < bb) && (maxx = bb)// this will be false
    console.log("maxx=", maxx);

    0 讨论(0)
  • 2020-12-02 22:52

    You can do something like this:

    (max < b) ? max = b : ''
    
    0 讨论(0)
提交回复
热议问题