首页 > 解决方案 > 如何在不使用新 if 语句的情况下比较特定值?

问题描述

我使用循环来比较来自 2 个不同对象的每一个值。因为当我想更改变量时,这种方式更简单易读,而不是仅仅使用大量if if if... 来逐一比较所有值。

这是代码:

  // Get values from the default and options
  var defaultValues = Object.values(this.getDefaults),
  newValues = Object.values(this.options);

  // Used loop for counting every single values from the Objects' 
  var checkDef = defaultValues.reduce((acc, cur) => acc + cur),
      checkNew = newValues.reduce((acc, cur) => acc + cur);

  // Compare between those 2 different variables.
  if (checkDef === checkNew) {
    console.log('true');
    setInterval(() => {
      this.runAnimate(this.initial[1], 1)
    }, this.getDefaults.countdown);
  } else {
    console.log('false');
    setInterval(() => {
      this.runAnimate(this.initial[1], 1)
    }, this.options.countdown);
  }

但是如果我想function根据不同的条件运行不同的代码,我将如何编写代码?

起初我试图做出新的if声明,但它会导致不必要的检查(字面意思是双重检查),因为我已经使用上面的循环比较了整个值。因此,给予另一个if完全是在浪费 imo。

  // Give another if to compare a specific condition
  if (this.getDefaults.skew === this.options.skew) {
     // ... execute function1
  else {
     // ... execute function2
  }

这是否不可避免地要给出另一个if陈述来比较我的案例中的特定值?

==== 进度更新 ====

我的目标是当调用的值pcSwipe是时true,通过执行来运行mousedown, swipeMove, swipeEnd函数$el.on({mousedown: ... })。但就像我在评论中说的那样,mousedown函数按条件数运行多次,每个值在和true之间有多少。这导致相同的方法。当您在移动语句上滑动屏幕时,它会移动 7 次行(因为是 7 次)。getDefaultValuesoptionsmobiletrue

JSFiddle

(function ($, window, undefined) {
  class Slider {
    // Get the default values
    get getDefaults() {
      const defaults = {
        autoSlide : true,
        countdown : 4000,
        direction : "left",
        display   : 1,
        loop      : true,
        pcSwipe   : false,
        verticle  : false,
        skew  : true,
      }
      return defaults;
    }
    constructor(options, initial) {
      this.getDefaults;
      this.initial = initial;
      this.initial[0].css({left: -100 + '%'});
      this.options = Object.assign(this.getDefaults, options);
    }

    // Swipe Event for PC
    mousedown(e) {
      console.log('text');
      e.stopPropagation();
    }
    swipeMove(e) {

    }
    swipeEnd(e) {

    }

    // Swipe Event for Mobile
    mdtouchStart(e) {
      this.coordX = e.touches[0].clientX;
      this.coordY = e.touches[0].clientY;
      return this.coordX, this.coordY;
    }
    mdtouchMove(e, initial) {
      var tx = e.touches[0].clientX,
      ty = e.touches[0].clientY,
      dist = Math.sqrt(tx + this.coordX);
    }
    mdtouchEnd(e, initial, defaults) {
      var dist = e.changedTouches[0].clientX - this.coordX,
        flood;
      if (dist > 200) {
        flood = -1;
        this.runAnimate(this.initial[1], flood);
      } else if (dist < -200) {
        flood = 1;
        this.runAnimate(this.initial[1], flood);
      } else {
        console.log('do nothing');
      }
      console.log(dist, this.initial[1]);
      e.stopPropagation();
    }

    // Set the function
    runAnimate(frame, direction) {
      if (!this.initial[1].is(':animated')) {
        this.initial[0].stop(true, true).animate({
          left: '-=' + (direction * 100) + '%'
        }, () => {
          this.initial[4] += direction;
          if (this.initial[4] > this.initial[5]) {
            this.initial[4] = 1;
            this.initial[0].css({
              left: -100 + '%'
            });
          } else if (this.initial[4] == 0) {
            this.initial[4] = this.initial[5];
            this.initial[0].css({
              left: (this.initial[5] * (-100)) + '%'
            });
          }
        })
      }
    }

    // Execute Method
    exe($el, initial, getDefaults) {
      console.log('no.4');

      // Distract values from the default and options

      Object.keys(this.getDefaults).forEach(key => {
        if (this.getDefaults[key] == this.options[key]) {
          $el.on({
            mousedown : (e) => this.mousedown(e),
            onmousemove : (e) => this.swipeMove(e),
            onmouseup   : (e) => this.swipeEnd(e, initial, getDefaults)
          });
        } else {
          $el.on({
            touchstart: (e) => this.mdtouchStart(e),
            touchmove : (e) => this.mdtouchMove(e),
            touchend  : (e) => this.mdtouchEnd(e, initial, getDefaults)
          });
        }
      });

      // Compare between those 2 different value bundles
      // var checkDef = defaultValues.reduce((acc, cur) => acc + cur),
      //     checkNew = newValues.reduce((acc, cur) => acc + cur);
      // if (checkDef === checkNew) {
      //   console.log('true');
      //   setInterval(() => {
      //     this.runAnimate(this.initial[1], 1)
      //   }, this.getDefaults.countdown);
      // } else {
      //   console.log('false');
      //   setInterval(() => {
      //     this.runAnimate(this.initial[1], 1)
      //   }, this.options.countdown);
      // }
    }
  }
  $.fn.bluSlider = function(options) {
    return this.each(function() {
      const $el = $(this);
      const initials = [
        myFrame = $el.find('.wrap'),
        myItems = myFrame.find('a'),
        myCloneFirst = myItems.first().before(myItems.last().clone()),
        myCloneLast = myItems.last().after(myItems.first().clone()),
        myCount = 1,
        myLength = myItems.length
      ];
      var Proto = new Slider(options, initials);
      Proto.exe($el);
    })
  }
}(jQuery));

$('.inline-grid').bluSlider({
  skew: false,
})
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
      * {
        margin: 0;
        padding: 0;
      }

      html, body
      {
        background-color: black;
      }

      .span2 {
        color: blue;
      }
      div {
        position: relative;
      }
      .inline-grid, .inline-grid2, .inline-grid3 {
        margin: 0 auto;
        width: 560px;
        border: 7px solid teal;
        display: flex;
        flex-flow: row;

        overflow: hidden;
      }
      .wrap {
        width: 100%;
        display: flex;
        flex-flow: row;
      }
      .cell {
        display: flex;
        flex-flow: column;
        flex-shrink: 0;

        width: 100%;
        height: 200px;
      }
      .orange {
        background-color: orange;
      }
      .blue {
        background-color: blue;
      }
      .crimson {
        background-color: crimson;
      }
      .green {
        background-color: green;
      }
    </style>
  </head>
  <body>
    <div id="slider" class="inline-grid">
      <div class="wrap">
        <a href="#" class="cell orange">

        </a>
        <a href="#" class="cell blue">

        </a>
        <a href="#" class="cell crimson">

        </a>
        <a href="#" class="cell green">

        </a>
      </div>
    </div>
    <br><br>
    <div id="slider2" class="inline-grid2">
      <div class="wrap">
        <a href="#" class="cell orange">

        </a>
        <a href="#" class="cell blue">

        </a>
        <a href="#" class="cell crimson">

        </a>
        <a href="#" class="cell green">

        </a>
      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </body>
</html>

标签: javascriptloopsclassobjectif-statement

解决方案


您可以遍历所有属性:

Object.keys(this.getDefaults).forEach(key => {
    if (this.getDefaults[key] == this.options[key]) {
        // execute function1
    } else {
        // execute function2
    }
});

推荐阅读