如何检查任意一个变量是否大于0

6

如何在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;
}
2个回答

8
您可以将这些变量合并到一个数组中,然后在其上运行 some 方法:

return [a, b, c, d].some(item => item > 0)


3

您可以将 && 运算符与三目运算符一起使用,如下所示:

(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/

这是一个JavaScript代码片段的链接,可以在浏览器中运行并测试代码。您可以编辑代码并立即看到结果。它对于IT技术人员进行代码测试和调试非常有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接