在不使用新的if语句的情况下,如何比较特定值?

时间:2019-03-21 04:02:59

标签: javascript loops class object if-statement

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

这是代码:

  // 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函数根据条件数量多次运行,truegetDefaultValues之间的每个值是options。这导致了mobile的相同方式。当您在移动对帐单上滑动屏幕时,它会移动7行(因为true为7)。

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>

1 个答案:

答案 0 :(得分:1)

您可以遍历所有属性:

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