How to write a ternary operator (aka if) expressio

2020-02-17 08:12发布

For example, something like this:

var value = someArray.indexOf(3) !== -1 ? someArray.indexOf(3) : 0

Is there a better way to write that? Again, I am not seeking an answer to the exact question above, just an example of when you might have repeated operands in ternary operator expressions...

17条回答
Emotional °昔
2楼-- · 2020-02-17 09:05

Use a helper function:

function translateValue(value, match, translated) {
   return value === match ? translated : value;
}

Now your code is very readable, and there's no repetition.

var value = translateValue(someArray.indexOf(3), -1, 0);

The hierarchy of coding concerns is:

  1. Correct (including true performance or SLA concerns)
  2. Clear
  3. Concise
  4. Fast

All the answers on the page so far appear to be correct, but I think my version has the highest clarity, which is more important than conciseness. If you don't count the helper function—as it can be reused—it is the most concise as well. The somewhat similar suggestion to use a helper function unfortunately uses a lambda that, to me, just obscures what it's doing. A simpler function with one purpose that doesn't take a lambda, just values, is to me much better.

P.S. If you like ES6 syntax:

const translateValue = (value, match, translated) => value === match ? translated : value;
let value = translateValue(someArray.indexOf(3), -1, 0); // or const
查看更多
▲ chillily
3楼-- · 2020-02-17 09:05

You could use re-assignment:

  • initialize variable to one value
  • use the serialization of the && operator for reassignment, because if the first condition is false, the second expression won't be evaluated

Ex.

var value = someArray.indexOf(3);
value == -1 && (value=0);

var someArray = [4,3,2,1];

var value = someArray.indexOf(1);
value == -1 && (value=0);
console.log('Found:',value);

var value = someArray.indexOf(5);
value == -1 && (value=0);
console.log('Not Found:',value);

查看更多
走好不送
4楼-- · 2020-02-17 09:06

This is a simple solution with bitwise NOT and a default value of -1 which results later to zero.

index = ~(~array.indexOf(3) || -1);

It works basically with a double bitwise NOT, which returns the original value or a default value, which after applying bitwise NOT returns zero.

Let's have a look to the table of truth:

 indexOf    ~indexOf   boolean    default     value      result         comment
---------  ---------  ---------  ---------  ---------  ---------  ------------------
      -1          0     falsy          -1         -1          0   take default value
       0         -1    truthy                     -1          0
       1         -2    truthy                     -2          1
       2         -3    truthy                     -3          2
查看更多
再贱就再见
5楼-- · 2020-02-17 09:07

Use an extract variable refactoring:

var index = someArray.indexOf(3);
var value = index !== -1 ? index : 0

It is even better with const instead of var. You could also do an additional extraction:

const index = someArray.indexOf(3);
const condition = index !== -1;
const value = condition ? index : 0;

In practice, use more meaningful names than index, condition, and value.

const threesIndex = someArray.indexOf(3);
const threeFound = threesIndex !== -1;
const threesIndexOrZero = threeFound ? threesIndex : 0;
查看更多
何必那么认真
6楼-- · 2020-02-17 09:11

Personally I find the best way to do this is still the good old if statement:

var value = someArray.indexOf(3);
if (value === -1) {
  value = 0;
}
查看更多
登录 后发表回答