简体   繁体   English

javascript 中 if/else 的简写

[英]Shorthand for if/else in javascript

I wrote the function to check if a given number is positive, negative, or zero.我写了 function 来检查给定的数字是正数、负数还是零。 Is there a shorthanded way?有捷径吗?

Is it possible to test the condition with map (using object to index the conditions)?是否可以使用 map 测试条件(使用 object 对条件进行索引)? i was inspired by second solution in this question but not sure how it applies here.我受到了这个问题中第二种解决方案的启发,但不确定它在这里如何应用。

const numCheck = (num) => {
  if (num == 0) {
    return "zero";
  } else {
    return num > 0 ? "positive" : "negative";
  }
};

const num1 = 3;
console.log(numCheck(num1));

 const numCheck = (num) => { return (num == 0)? "zero": ((num > 0)? "positive": "negative"); }; const num1 = 3; console.log(numCheck(num1));

you can do that, simply use Math.sign() :你可以这样做,只需使用Math.sign()

 const numCheck = n => ['negative','zero','positive'][1+Math.sign(n)] console.log( numCheck( 4 ) ) console.log( numCheck( 0 ) ) console.log( numCheck( -3 ) )

A shorter solution:更短的解决方案:

 var numCheck = (num) => num == 0? "zero": num > 0? "positive": "negative"; const num1 = 3; console.log(numCheck(num1));

Inspired by Mister Jojo answer but without Math.sign灵感来自 Jojo 先生的回答,但没有Math.sign

 const sign = x => ['negative','zero','positive'][1 + (x > 0) - (x < 0)] console.log(sign(10)) // positive console.log(sign(0)) // zero console.log(sign(-20)) // negative

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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