removing item from array after match

This question already has an answer here:

  • How do I remove a particular element from an array in JavaScript? 62 answers

  • 试试这可能对你有帮助

    function arr_diff(a1, a2)
    {
      var a=[], diff=[];
      for(var i=0;i<a1.length;i++)
        a[a1[i]]=true;
      for(var i=0;i<a2.length;i++)
        if(a[a2[i]]) delete a[a2[i]];
        else a[a2[i]]=true;
      for(var k in a)
        diff.push(k);
      return diff;
    }
    var a = [1,2,3,4,5,6]
    var b = [2,3]
    console.log(arr_diff(a,b));
    

    There are several errors here. First of all, jQuery's inArray searches for elements, not subArrays. So you might conceivably imagine that you would find that

    $.inArray([2, 3], [[1, 2], [2, 3], [3, 4], [4, 5]])
    

    would yield 1 , but in fact even that won't work, because it follows the Array.prototype standards and compares with reference equality.

    It certainly won't find the array [2, 3] as an element of [1, 2, 3, 4, 5] .

    Next, if it did happen to find that array, Array.prototype has no remove function.

    You might want to look at Array.prototype.splice() .


    Here is one option ( arraysEqual() borrowed from this answer):

    function arraysEqual(a, b) {
        if (a === b) return true;
        if (a == null || b == null) return false;
        if (a.length != b.length) return false;
    
        for (var i = 0; i < a.length; ++i) {
            if (a[i] !== b[i]) return false;
        }
        return true;
    }
    
    for (var i = 0; i <= a.length - b.length; i++) {
        var slice = a.slice(i, i + b.length);
        if (arraysEqual(slice, b)) {
            a.splice(i, b.length);
        }
    }
    

    This loops through a comparing slices of a to b , and removing that slice when a match is found.

    链接地址: http://www.djcxy.com/p/3224.html

    上一篇: 在for中删除JArray的元素

    下一篇: 比赛结束后从阵列中移除物品