[英]How to check if any one of the variable is greater than 0
如何从Typescript中的给定变量检查是否有任何变量大于0?
如何重写下面的代码,使其更优雅/简洁?
checkIfNonZero():boolean{
const a=0;
const b=1;
const c=0;
const d=0;
//Regular way would be as below.
//How can this use some library instead of doing comparison for each variable
if(a>0 || b>0 || c>0 || d>0){
return true;
}
return false;
}
您可以将变量组合到一个数组中,然后在其上运行一些 :
return [a, b, c, d].some(item => item > 0)
您可以将&&
运算符与ternary operator
组合使用,如下所示:
(a && b && c && d > 0) ? true : false // will return true if all integers are more than 0
jsFiddle: https ://jsfiddle.net/AndrewL64/6bk1bs0w/
或者您可以将变量分配给数组并使用Array.prototype.every(),如下所示:
let x = [a, b, c, d]
x.every(i => i > 0) // will return true if all integers are more than 0
jsFiddle: https ://jsfiddle.net/AndrewL64/6bk1bs0w/1/
或者为了使上面更短,你可以直接将值放在一个数组中,并直接使用数组中的every
,如下所示:
[0, 1, 0, 0].every(i => i > 0); // will return false since all integers are not more than 0
jsFiddle: https ://jsfiddle.net/AndrewL64/6bk1bs0w/3/
或者你可以创建一个可重复使用的函数,并且只需要一行就可以多次运行它:
function moreThanOne(...args){
// Insert any of the above approaches here but reference the variables/array with the word 'arg'
}
moreThanOne(3,1,2,0); // will return false as well as alert false
moreThanOne(3,1,2,4); // will return true as well as alert true
jsFiddle: https ://jsfiddle.net/AndrewL64/6bk1bs0w/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.