Return result from Ternary in one line (JavaScript)

对着背影说爱祢 提交于 2021-02-17 07:22:45

问题


In JavaScript, rather than having to assign the result to a variable, is it possible to return the result of a ternary in one line of code?

e.g. Instead of this:

function getColor(val){
    var result = val <= 20 ? '#000' : val >= 80 ? '#999' : '#555';
    return result;
}

Can we do something like this...

function getColor(val){
    return val <= 20 ? '#000' : val >= 80 ? '#999' : '#555';
}

I am asking this because I just tried the above and nothing was returned.


回答1:


Yes. It's possible. Also you can make your code even more compact.

function isAGreaterThanB(){
    return a > b;
}

Above code will return true if a is greater, false if not.




回答2:


You can just return whatever a > b evaluates to.

 function isAGreaterThanB(){
     return a > b;
 }

As a > b evaluates to either True or False, you can just return that value directly.

Actually doing it how you typed is, is a really bad way to do it and is unneccessarily complicated for something as basic as this.




回答3:


Yes it is possible, you could for example say this:

function getBiggerNumber(a, b){
    return a > b ? a : b
}

this function returns a if a is bigger than b and b if b is bigger than a.
Just for completeness: It would also return b if a and b would be equal



来源:https://stackoverflow.com/questions/27039849/return-result-from-ternary-in-one-line-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!