简体   繁体   中英

Using ternary operator instead of if/else in javascript

Say you have a simple array with random numbers, given the following code, how would i reduce the line of code to use a ternary operator to render the following.

[1, 2, 1, 4, 6]

 let arr = [1, 2, 3, 4, 6, 8, 9, 12, 13, 15]; let myArray = arr.map((val, i, arr) => { if (val % 2 === 0) { return val } else { return val % 2 } }); console.log(myArray) 

Logical OR can do the trick for you.

 let arr = [1,2,3,4,6,8,9,12,13,15] let myArray = arr.map((val) => val % 2 || val); console.log(myArray) 

You could take a bitwise AND & or (with logical OR || ) the value, instead of a conditional (ternary) operator ?: .

Bitwise AND with a value of one returns either one or zero, depending on the other operand.

 var array = [1, 2, 3, 4, 6, 8, 9, 12, 13, 15], result = array.map(v => v & 1 || v); console.log(result); 

Just write the ternary condition as a single liner:

 const arr = [1,2,3,4,6,8,9,12,13,15]; const myArray = arr.map((val) => val % 2 === 0 ? val: val % 2); console.log(myArray); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM