【问题标题】:How to check if any one of the variable is greater than 0如何检查任何一个变量是否大于0
【发布时间】:2018-05-16 22:47:44
【问题描述】:

如何检查 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;
}

【问题讨论】:

    标签: javascript angular reactjs typescript


    【解决方案1】:

    您可以将变量组合成一个数组,然后在其上运行some

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

    【讨论】:

      【解决方案2】:

      您可以像这样将&& 运算符与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/

      【讨论】:

        猜你喜欢
        • 2011-11-20
        • 1970-01-01
        • 2019-11-17
        • 2021-03-28
        • 2012-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多