suchen

Heim  >  Fragen und Antworten  >  Hauptteil

javascript – So entfernen Sie mehrere Werte aus einem Array und stellen nur den Index des Arrays bereit

Durch das Entfernen von Splice werden das Array und die Indizes ständig verändert, sodass die Indizes, an die ich mich zuvor erinnerte, nutzlos sind.

巴扎黑巴扎黑2794 Tage vor964

Antworte allen(5)Ich werde antworten

  • 阿神

    阿神2017-06-30 10:01:33

    先删除下标大的再删除下标小的

    Antwort
    0
  • 代言

    代言2017-06-30 10:01:33

    把数组换成对象,使用delete方法删除,下标就不会变了

    Antwort
    0
  • 漂亮男人

    漂亮男人2017-06-30 10:01:33

    数组的map方法 剔除指定的索引位置的元素 新生成一个数组

    或者直接filter方法

    Antwort
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-30 10:01:33

    可以试一下,新建一个新的数组,然后循环你要做修改的那个数组,如果下标不是你要删的那个数,那就把这个位置上的元素push到你的新的数组里,如果下标是你要删的那个数,直接continue跳出循环
    这样循环结束之后,新的数组就是你需要的数组,再把它赋值给旧数组就好了

    Antwort
    0
  • 学习ing

    学习ing2017-06-30 10:01:33

    生成新数组的话:

    arr = [1,2,3,4,5,6,7]
    removes = [1,3,5]
    arr = arr.filter(function(value, index) { 
        return removes.indexOf(index) < 0
    });

    不生成新数组:

    arr = [1,2,3,4,5,6,7]
    removes = [1,3,5]
    Array.prototype.remove = function(removes){
        removes.sort(function(a, b) {
            return a - b;
        }).reverse().forEach(function(value){this.splice(value, 1)
       }.bind(this)
    )};
    arr.remove(removes)

    Antwort
    0
  • StornierenAntwort