【问题标题】:Array forEach skips odd indices数组 forEach 跳过奇数索引
【发布时间】:2016-01-20 09:23:10
【问题描述】:

需要删除以nf- 为前缀的元素上的某些类并保留所有其他类。元素可能有一个或多个带有上述前缀的类。

<div class="custom-nf">
  <div class="input nf-input-outer nf-validation">
    <div class="nf-container">
      <div class="nf-outer nf-outer-input nf-outer-validation">
        <div class="nf-middle">
          <div class="nf-inner">
            <label for="dummy" class="nf-label"></label>
            <input id="dummy" type="text" class="nf-input"></div>
        </div>
      </div>
    </div>
  </div>
</div>

我有下面的脚本,它获取类前缀为 nf- 的所有元素,然后为每个元素查看 classList 属性,并为每个类确定当前类字符串是否与正则表达式中定义的前缀匹配。如果为 true,则从元素中删除该类。

(function(){
  // get elements with nf- prefix class
  var nfClasses = document.querySelectorAll('.custom-nf [class*="nf-"]');
  // each element found
  Array.prototype.forEach.call(nfClasses, function(element){
    // each class per element with classList
    Array.prototype.forEach.call(element.classList, function(el){
      // only for classes that match prefix nf-
      if (el == el.match(/^nf-.*/g)) {
        // remove nf- class from the element
        element.classList.remove(el);
      }
    });
  });
})();

现在代码似乎可以正常运行并删除带有前缀的类,但内部 forEach 部分不会删除在 classList 数组中显示为奇数索引的类。这是代码运行后 HTML 的样子:

<div class="custom-nf">
  <div class="input nf-validation">
    <div class="">
      <div class="nf-outer-input">
        <div class="">
          <div class="">
            <label for="dummy" class=""></label>
            <input id="dummy" type="text" class=""></div>
        </div>
      </div>
    </div>
  </div>
</div>

运行代码将减少剩余的类,以此类推,直到所有类都消失,但这不切实际,并且不知道一个元素可能有多少个带有前缀的类。

如果你想看一看,我有一个 JSFiddle 正在运行。

为什么内部 forEach 会跳过奇数索引,我该如何纠正?

【问题讨论】:

  • 我不确定,所以我不会回答这个问题,但我猜想从回调内部修改 element.classList 会改变指针,因此跳过旁边的元素一个刚刚删除。

标签: javascript html regex


【解决方案1】:

从回调内部修改 element.classList 会更改数组的索引,因此会跳过刚刚删除的元素旁边的元素。

只需更改外部回调:

(function() {
  // get elements with nf- prefix class
  var nfClasses = document.querySelectorAll('.custom-nf [class*="nf-"]');
  // each element found
  Array.prototype.forEach.call(nfClasses, function(element) {
    // here you gather class names to remove
    var toRemove = [];

    // each class per element with classList
    Array.prototype.forEach.call(element.classList, function(el) {
      // only for classes that match prefix nf-
      if (el.match(/^nf-.*/)) {
        // remove nf- class from the element
        toRemove.push(el);
      }
    });

    // now actually remove those classes
    toRemove.forEach(function(el) {
      element.classList.remove(el);
    });
  });
})();

https://jsfiddle.net/fcu1ypds/5/查看它的实际应用

【讨论】:

  • 每次删除后数组都变短了,这很明显,现在你指出来了。我猜我认为数组长度不会受到影响,直到每个数组的 forEach 循环完成;在所有循环完成之前存储索引。非常感激。谢谢大家。
猜你喜欢
  • 2018-05-28
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 2013-03-30
  • 1970-01-01
相关资源
最近更新 更多