有没有更优雅的方式来写这些条件?

时间:2018-08-05 21:28:39

标签: javascript loops if-statement conditional

    if(first - second >=2 || first - second <=-2 || first - third >=2 || first - third <=-2 || second - third >=2 || second - third <=-2)

令人恶心。

我需要检查三个值,如果其中两个值相差> = 2,那么我将执行一些任务。

我很好奇,您能提出一种使它变得更愉快的方法吗?谢谢

6 个答案:

答案 0 :(得分:4)

if ( Math.max(first, second, third) - Math.min(first, second, third) >= 2 )

或效率较低:

var a = [first, second, third].sort((a, b) => a - b));
if ( a[2] - a[0] >= 2 )

答案 1 :(得分:3)

将减法表达式放入数组中,并使用Array#some()和Math.abs

<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Diagnostics.Eventing.Reader.EventLogRecord</T>
      <T>System.Diagnostics.Eventing.Reader.EventRecord</T>
      <T>System.Object</T>
    </TN>
    <ToString>System.Diagnostics.Eventing.Reader.EventLogRecord</ToString>
    <Props>
      <I32 N="Id">100</I32>
      <Nil N="Version" />
      <I32 N="Qualifiers">0</I32>
      <By N="Level">4</By>
      <I32 N="Task">0</I32>
      <Nil N="Opcode" />
      <I64 N="Keywords">36028797018963968</I64>
      <I64 N="RecordId">4824</I64>
      <S N="ProviderName">CCS LOGGING</S>
      <Nil N="ProviderId" />
      <S N="LogName">CCS</S>
      <Nil N="ProcessId" />
      <Nil N="ThreadId" />
      <S N="MachineName">Test</S>
      <Nil N="UserId" />
      <DT N="TimeCreated">2018-08-03T11:57:53-04:00</DT>
      <Nil N="ActivityId" />
      <Nil N="RelatedActivityId" />
      <S N="ContainerLog">ccs</S>
      <Obj N="MatchedQueryIds" RefId="1">
        <TN RefId="1">
          <T>System.UInt32[]</T>
          <T>System.Array</T>
          <T>System.Object</T>
        </TN>
        <LST />
      </Obj>
      <Obj N="Bookmark" RefId="2">
        <TN RefId="2">
          <T>System.Diagnostics.Eventing.Reader.EventBookmark</T>
          <T>System.Object</T>
        </TN>
        <ToString>System.Diagnostics.Eventing.Reader.EventBookmark</ToString>
      </Obj>
      <S N="LevelDisplayName">Information</S>
      <S N="OpcodeDisplayName">Info</S>
      <Nil N="TaskDisplayName" />
      <Obj N="KeywordsDisplayNames" RefId="3">
        <TN RefId="3">
          <T>System.Collections.ObjectModel.ReadOnlyCollection`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
          <T>System.Object</T>
        </TN>
        <LST>
          <S>Classic</S>
        </LST>
      </Obj>
      <Obj N="Properties" RefId="4">
        <TN RefId="4">
          <T>System.Collections.Generic.List`1[[System.Diagnostics.Eventing.Reader.EventProperty, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
          <T>System.Object</T>
        </TN>
        <LST>
          <Obj RefId="5">
            <TN RefId="5">
              <T>System.Diagnostics.Eventing.Reader.EventProperty</T>
              <T>System.Object</T>
            </TN>
            <ToString>System.Diagnostics.Eventing.Reader.EventProperty</ToString>
            <Props>
              <S N="Value">Timestamp: 8/3/2018 3:57:53 PM_x000D__x000A_Message: &lt;Exception handlingInstanceId="7bdbceed-ef96-4f0d-985a-88f7c8641661"&gt;_x000D__x000A_  &lt;DateTime&gt;2018-08-03 11:57:53Z&lt;/DateTime&gt;_x000D__x000A_  &lt;Message&gt;Exception Message Key:RDKEYNF_x000D__x000A_Exception Message:No record found in ApplicationLabels category for key = R-MD, Locale = 1033, Filter = Active, and EffectiveDate = 8/3/2018.&lt;/Message&gt;_x000D__x000A_  &lt;Source&gt;AFS&lt;/Source&gt;_x000D__x000A_  &lt;HelpLink /&gt;_x000D__x000A_  &lt;Property name="Parameters"&gt;_x000D__x000A_[CategoryName] : ApplicationLabels_x000D__x000A_[Key] : R-MD_x000D__x000A_[LocaleId] : 1033_x000D__x000A_</S>
            </Props>
          </Obj>
        </LST>
      </Obj>
    </Props>
    <MS>
      <S N="Message">Timestamp: 8/3/2018 3:57:53 PM_x000D__x000A_Message: &lt;Exception handlingInstanceId="7bdbceed-ef96-4f0d-985a-88f7c8641661"&gt;_x000D__x000A_  &lt;DateTime&gt;2018-08-03 11:57:53Z&lt;/DateTime&gt;_x000D__x000A_  &lt;Message&gt;Exception Message Key:RDKEYNF_x000D__x000A_Exception Message:No record found in ApplicationLabels category for key = R-MD, Locale = 1033, Filter = Active, and EffectiveDate = 8/3/2018.&lt;/Message&gt;_x000D__x000A_  &lt;Source&gt;AFS&lt;/Source&gt;_x000D__x000A_  &lt;HelpLink /&gt;_x000D__x000A_  &lt;Property name="Parameters"&gt;_x000D__x000A_[CategoryName] : ApplicationLabels_x000D__x000A_[Key] : R-MD_x000D__x000A_[LocaleId] : 1033_x000D__x000A_</S>
    </MS>
  </Obj>
</Objs>

答案 2 :(得分:2)

您可以使用Math.abs()简单地将if语句分解为3个条件。 就是这样:

if( Math.abs( first - second ) >= 2 || Math.abs( first - third ) >= 2 || Math.abs( second - third ) >= 2 ) 

Math.abs()函数返回其参数的绝对值。

答案 3 :(得分:1)

如果您愿意使用函数来确定数字数组之间的最大差值,则可以通过以下几种方法来解决该问题。最短的可能是最简洁的方法,只是一些有关如何解决问题的想法:

const shortGetMaxDifference = numbers => Math.max(...numbers) - Math.min(...numbers);

const getMaxDifference = numbers => {
  const sorted = numbers
    .sort((a, b) => a > b ? -1 : 1)
    
  return sorted[0] - sorted[sorted.length-1]
}

const longWindedGetMaxDifference = numbers => numbers
  .map(i => numbers.map(j => Math.max(i, j) - Math.min(i, j))
  .sort((a, b) => a > b ? -1 : 1))
  .reduce((prev, curr) => [...prev, ...curr], [])
  .sort((a, b) => a > b ? -1 : 1)[0]
  
const numbers = [1, 4, -5, 7, 13]

console.log(shortGetMaxDifference(numbers))
console.log(getMaxDifference(numbers))
console.log(longWindedGetMaxDifference(numbers))

const first = 1;
const second = 3;
const third = 2;

if (getMaxDifference([first, second, third]) >= 2) {
  console.log('The difference is bigger');
}

答案 4 :(得分:0)

Math.abs()将为您提供帮助,您可以将几个条件分解为3个条件。

Math.abs(first - second) >= 2和其他类似

答案 5 :(得分:0)

一种(客观上)更优雅的方法是利用Math.abs()函数:

#E {
  min-height: 10%;
  max-height: 40%;
}

一种主观的(我可能完全没有必要添加),使其在美学上更令人愉悦:

if (Math.abs(first-second) >= 2 || Math.abs(first-third) >= 2 || Math.abs(second-third) >= 2)){
    // do something
}

但是我通常不建议这样做。虽然它可以节省您几秒钟编写一些function plusminus2(val1, val2){ return ((Math.abs(val1 - val2) >= 2) ? true : false); } if (plusminus2(first, second) || plusminus2(first, third) || plusminus2(second, third)){ // do something } 语句(假设有不止一个),但它将使其他任何试图理解您的代码甚至您自己的人都感到头疼如果您将其打开4年!