How can I check if any of the variables is greater than 0 from given variable in Typescript?
How can I rewrite below code so that it's more elegant/concise?
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)
You can combine the &&
operator with the ternary operator
like this:
(a && b && c && d > 0) ? true : false // will return true if all integers are more than 0
jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/
OR you can assign the variables to an array and use Array.prototype.every() like this:
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/
OR to make the above even shorter, you can directly place the values in an array and use every
on the array directly like this:
[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/
OR you can make a reusable function once and run it multiple times with just one line like this:
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
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.