javascript - 将方法 hide/show 传递给另一个方法

标签 javascript jquery string methods

我在代码中以两种方式调用对象方法:

this.reveal.updateVisuals(i, 'show');

this.reveal.updateVisuals(i, 'hide');

我将隐藏和显示条件作为字符串传递,以便稍后进行评估并用作方法。请注意条件:if (effect === 'show/hide')。

 updateVisuals: function (time, effect) {
      // Check if parameter exists and property can be read
      if (this.breakpointsMap && typeof this.breakpointsMap[checkTime] !== "undefined") {
        if (effect === 'show') {
          // display the items that were fast forwarded
          var k = this.breakpointsMap[checkTime].length;
          while (k--) {
            try {
              this.breakpointsMap[checkTime][k].show();
            } catch (err) {}
          }
        } else if (effect === 'hide') {
          // display the items that were fast forwarded
          var k = this.breakpointsMap[checkTime].length;
          while (k--) {
            try {
              this.breakpointsMap[checkTime][k].hide();
            } catch (err) {}
          }
        }
      }
    }

但是代码似乎是重复的,我想知道是否有一种方法可以将 hide 或 show 作为方法传递给该方法,并在需要时将其应用到数组上。我尝试过这样的事情:

this.reveal.updateVisuals(i).show

最佳答案

您可以使用多种方法来简化此操作,以下是其中几种:

updateVisuals: function (time, effect) {
  if (this.breakpointsMap && typeof this.breakpointsMap[checkTime] !== "undefined") {
      this.breakpointsMap[checkTime].forEach(e => e[effect]());
  }
}

或者返回数组:

updateVisuals: function (time, effect) {
  if (this.breakpointsMap && typeof this.breakpointsMap[checkTime] !== "undefined") {
      return this.breakpointsMap[checkTime];
  }else{
      return [];
  }
}

this.reveal.updateVisuals(i).forEach(e => e.show());

关于javascript - 将方法 hide/show 传递给另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46564965/

相关文章:

javascript - 参数分隔符的正则表达式帮助

javascript - 刷新slidejs

javascript - 将 Bower 组件安装到两个不同的目录中?

javascript - JQuery onpaste 事件限制用户粘贴字符,如 | , ./

javascript - 多个对象属性 JavaScript

jQuery,选择更改时的事件

javascript - 从隐藏字段获取值 - JavaScript

python - 如何在 Python fstring 中使用变量,同时包含不转义下一个字符的反斜杠

java - java中的不可变字符串?

python - 如何从 python 列表中的字符串中删除双引号?