使用此特定代码从另一个数组中删除一个数组

时间:2013-08-13 14:22:12

标签: javascript jquery

我有以下数组,它包含其他数组(它们实际上是html5画布的坐标)。

var crossesPos = [[317, 193], [110, 334], [390, 347], [281, 222], [307, 384], [329, 366], [230, 104], [276, 156], [173, 330], [227, 100], [397, 261], [341, 389], [233, 223], [261, 350], [267, 286]]

不要说:

x = 317;
y = 193;

在以下函数中,如何从crossesPos中删除数组[317,193]?

function checkForCrosses(x,y){
    var position;
    jQuery.each(crossesPos, function(){
        position = this;
        if(x == position[0] && y == position[1]){
            // how do I remove the array [317,193] from crossesPos?
        }
    });
}

泰!

8 个答案:

答案 0 :(得分:5)

使用以下代码拼接数组中的确切坐标。将此代码放在您的函数中。这比JQuery代码更有效。

Pure JavaScript

for(var i=0; i<crossesPos.length; i++)
{
    if(crossesPos[i][0] === x)
        if(crossesPos[i][1] === y)
        {
            crossesPos.splice(i,1);
            break;
        }
}

重要提示:如果您要删除所有数组中匹配的元素(而不仅仅是一个),您必须编辑代码,删除break;条件和反转循环

for(var i=crossesPos.length-1; i>=0; i--)
{
     if(crossesPos[i][0] === x)
        if(crossesPos[i][1] === y) crossesPos.splice(i,1);          
}

Working demo (with sexy output)


Performance comparison (test it yourself!)

这是(在本文发布时)最有效和最高效的方式来执行您的需求,因为最接近的结果仍然比我的回答<强>〜90%慢。

Performance comparison

答案 1 :(得分:3)

执行此操作的“jQuery方式”是使用jQuery.grep()

var crossesPos = [[317, 193], [110, 334], [390, 347], [281, 222], [307, 384],
                  [329, 366], [230, 104], [276, 156], [173, 330], [227, 100],
                  [397, 261], [341, 389], [233, 223], [261, 350], [267, 286]];

crossesPos = jQuery.grep(crossesPos,
                         function(e) { return e[0] === 317 && e[1] === 193; },
                         true);

(See it run)

答案 2 :(得分:3)

使用jQuery的 grep 效用函数:

var x = 317,
    y = 193,
    newPos = $.grep(crossesPos, function(n, i){
          return (n[0] != x || n[1] != y);
    });

答案 3 :(得分:2)

您应该使用.splice()函数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

crossesPos.splice(index,1);

答案 4 :(得分:2)

我认为您需要使用splice()来删除找到的项目。 This是一个有效的工作。打开控制台以查看修改过的数组。

要添加到您的功能的代码:

function checkForCrosses(x, y){
    var position,
        length = crossesPos.length;

    for (var i = length; i > 0; i--) {
      position = crossesPos[i - 1];

      if (x == position[0] && y == position[1])
        crossesPos.splice(i - 1, 1);
    }
}

答案 5 :(得分:1)

http://underscorejs.orghttp://lodash.com可以让这更容易,但如果你坚持直接做到这一点:

var pos = -1;
jQuery.each(crossesPos,function(idx,item) {
  if (x===item[0] && y===item[1]) {
    pos = idx;
  }
});
crossesPos.splice(idx,1);

或更简单

var ary = [];
jQuery.each(crossesPos,function(idx,item) {
  if (x!==item[0] || y!==item[1]) {
    ary.push(item);
  }
});
crossesPos = ary;

答案 6 :(得分:1)

使用filter

function checkForCrosses(x,y){
    function myFilter(element, index, array) {
        return (element[0] != x || element[1] != y);
    }
    crossesPos = crossesPos.filter(myFilter);
}

然后crossesPos保留不带[317, 193]

的数组

答案 7 :(得分:1)

//
//
//  here's some common Array operations you might find usefull and familiar: 
//   
// .each( callback, boolFlgFromLast )
//   # iterate an array runing given callback-fn for every array item, 
//   # pass it curent array key and value, respectively, 
//   # set context of the callback to host array, 
//   # if boolFlgFromLast argument is ( === )true, iterate from last element, 
//   # break iteration if callback returns ( === )false, 
//   # return iterated array
//
// .not( callback ) 
//   # remove items for which callback returns ( === )true
//   # keep others
//   # return host array
//  
// .keep( callback )
//   # keep items for which callback returns ( === )true
//   # remove others
//   # return host array
//
// .desparse()
//   # 'desparse' host array in place
//   # return host array
// 
//
//    var
//       a = [ 
//               [317, 193], 
//               [110, 334], 
//               [390, 347], 
//            ];
//    
//  
//    a
//     .each( function ( k, v ) { console.log('['+ k +'] -> '+ v ); } )
//     .not(  function ( k, v ) { console.log(' * '); return ( v[0] == 317 ) && ( v[1] == 193 ); } )
//     .each( function ( k, v ) { console.log('['+ k +'] -> '+ v ); } )
//     .keep( function ( k, v ) { console.log(' * '); return Math.random() > .1; } )
//     .each( function ( k, v ) { console.log('['+ k +'] -> '+ v + ', [ this === a ] -> '+ ( this === a )  ); } );
//       
//     // make sparse array
//     a[5] = [0,0];
//     console.log('sparse array: ', a);
//     
//     a
//     .desparse()
//     .each( function ( k, v ) { console.log('['+ k +'] -> '+ v ); } )
//       
//
//
;( function( _a ) { 

    var
        t  = !0, 
        f  = !t;

    _a.each = function ( fn ) { 

                    var
                       len = this.length, 
                       i   = 0;

                    for( ; i < len ; i++ ) { 
                       if ( fn.call( this, i, this[i] ) === f ) break;
                    }

                    return this;

    };

    overload( 'each', _a, function ( fn, flgIterateBackwards ) {

                              if ( flgIterateBackwards === t ) {

                                  var
                                     i = this.length - 1;

                                   for ( ; i >= 0 ; i-- ) { 
                                       if ( fn.call( this, i, this[i] ) === f ) break;
                                   }

                                   return this;

                              } else {

                                  return this.each( fn );

                              }
                          } 
            );

    _a.not = function ( callback ) { 
                  return this.each( function ( k, v ) { 
                                      ( callback.call( this, k, v ) === t ) && this.splice( k, 1 );
                                    }, t );
             };

    _a.keep = function ( callback ) { 
                  return this.each( function ( k, v ) { 
                                       ( callback.call( this, k, v ) === t ) || this.splice( k, 1 );
                                    }, t );
              };


    _a.desparse = function () { 
        return this.not( function ( k, v ) { return k in this === f; } );
    };


    // helper fn-s

    function overload ( fn, obj,  newfn ) { 

       return ( function ( origfn ) { 

            obj[fn] = function () {

                        var
                            args = _a.slice.call( arguments );

                        if ( newfn.length == arguments.length ) {

                            return newfn.apply( this, args )

                        } else if ( isfn ( origfn ) ) {

                            return origfn.apply( this, args )

                        } else {
                            // ignore non method props
                        }

                      };

        } )( obj[fn] );
     }  

    function isfn ( o ) { 
       return ( typeof o === 'function' ) && 
              ( Object.prototype.toString.call( o ) === '[object Function]' );
    }


} )( Array.prototype );

//