2012-05-29 19 views
7

puede alguien decirme cómo puedo eliminar elemento de cadena de una matriz tengo google esto y todo lo que consigo es la eliminación por número de índicequitar elemento de cadena de javascript gama

mi ejemplo:

var myarray = ["xyz" , "abc" , "def"] ; 
var removeMe = "abc" ; 

    myarray.remove(removeMe) ; 
    consle.log(myarray) ; 

esto es lo que me sale de la consola:

Uncaught TypeError: Object xyz,abc,def has no method 'remove' 

jsfiddle

Respuesta

6

De https://stackoverflow.com/a/3955096/711129:

Array.prototype.remove= function(){ 
    var what, a= arguments, L= a.length, ax; 
    while(L && this.length){ 
     what= a[--L]; 
     while((ax= this.indexOf(what))!= -1){ 
      this.splice(ax, 1); 
     } 
    } 
    return this; 
} 
var ary = ['three', 'seven', 'eleven']; 

ary.remove('seven') 

o, lo que es una función global:

function removeA(arr){ 
var what, a= arguments, L= a.length, ax; 
while(L> 1 && arr.length){ 
    what= a[--L]; 
    while((ax= arr.indexOf(what))!= -1){ 
     arr.splice(ax, 1); 
    } 
} 
return arr; 
} 
var ary= ['three','seven','eleven']; 
removeA(ary,'seven') 

Tienes que hacer una función de sí mismo. Puede recorrer el conjunto y eliminar el elemento desde allí, o hacer que esta función lo haga por usted. De cualquier manera, no es una característica estándar de JS.

5

Trate como a continuación,

myarray.splice(myarray.indexOf(removeMe),1); 

Puede agregar este script a continuación (from MDN) para los navegadores que no soportan indexOf

if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function (searchElement /*, fromIndex */) { 
     "use strict"; 
     if (this == null) { 
      throw new TypeError(); 
     } 
     var t = Object(this); 
     var len = t.length >>> 0; 
     if (len === 0) { 
      return -1; 
     } 
     var n = 0; 
     if (arguments.length > 0) { 
      n = Number(arguments[1]); 
      if (n != n) { // shortcut for verifying if it's NaN 
       n = 0; 
      } else if (n != 0 && n != Infinity && n != -Infinity) { 
       n = (n > 0 || -1) * Math.floor(Math.abs(n)); 
      } 
     } 
     if (n >= len) { 
      return -1; 
     } 
     var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); 
     for (; k < len; k++) { 
      if (k in t && t[k] === searchElement) { 
       return k; 
      } 
     } 
     return -1; 
    } 
} 
+4

Un comentario, algunos navegadores no soportan 'indexOf' – jwatts1980

+1

Además, si' indexOf' no encuentra el elemento, usted va a empalme con el índice '-1' que sigue elimina una elemento – Esailija

16

Dado que está utilizando jQuery

myarray.splice($.inArray("abc", myarray), 1);

EDIT Si el artículo no está en la matriz, es probable que este "one-liner" arroje un error. Algo un poco mejor

var index = $.inArray("abc", myarray); 
if (index>=0) myarray.splice(index, 1); 
+2

No necesita usar jQuery para esto. –

+3

Algunos navegadores no son compatibles con 'indexOf'. "InArray" de Jquery abstraerá la funcionalidad del navegador. – jwatts1980

+0

+1 para usar '> = 0' http://jsperf.com/not-vs-gt-vs-ge/4 (y para la respuesta correcta de c) – ajax333221