2010-08-02 9 views

Respuesta

23

Puede utilizar each() ...

// Iterate over an array of strings, select the first elements that 
// equalsIgnoreCase the 'matchString' value 
var matchString = "MATCHME".toLowerCase(); 
var rslt = null; 
$.each(['foo', 'bar', 'matchme'], function(index, value) { 
    if (rslt == null && value.toLowerCase() === matchString) { 
    rslt = index; 
    return false; 
    } 
}); 
+2

Querrá agregar un "return false;" al final de esa declaración if para que 'cada' no continúe después de encontrar un elemento coincidente. (En jQuery.each() "return false;" es equivalente a "break;" en un bucle de JavaScript normal.) –

+3

¿No es para LowLase en lugar de para Low? – Sarfraz

+0

@Jordan y @Sarfraz: ambos puntos buenos –

1

No. Tendrá que jugar con sus datos, generalmente hago todas mis cadenas en minúscula para facilitar las comparaciones. También existe la posibilidad de utilizar una función de comparación personalizada que haría las transformaciones necesarias para que la comparación no sea sensible.

1

podría recorrer la matriz y ToLower cada elemento y ToLower lo que estás buscando, pero en ese punto en el tiempo, es posible que también acaba de compararlo en lugar de utilizar InArray()

1

Parece que debe implementar su propia solución para esto. Here es un buen artículo sobre cómo agregar funciones personalizadas a jQuery. Solo necesitará escribir una función personalizada para repetir y normalizar los datos y luego compararlos.

4

Gracias a @Drew Wills.

Reescribí como esto:

function inArrayCaseInsensitive(needle, haystackArray){ 
    //Iterates over an array of items to return the index of the first item that matches the provided val ('needle') in a case-insensitive way. Returns -1 if no match found. 
    var defaultResult = -1; 
    var result = defaultResult; 
    $.each(haystackArray, function(index, value) { 
     if (result == defaultResult && value.toLowerCase() == needle.toLowerCase()) { 
      result = index; 
     } 
    }); 
    return result; 
} 
+1

Esto funcionó perfectamente para mí. – Alan

1

En estos días yo prefiero usar underscore para las tareas de la siguiente manera:

a = ["Foo","Foo","Bar","Foo"]; 

var caseInsensitiveStringInArray = function(arr, val) { 
    return _.contains(_.map(arr,function(v){ 
     return v.toLowerCase(); 
    }) , val.toLowerCase()); 
} 

caseInsensitiveStringInArray(a, "BAR"); // true 
24

En caso de que alguien quería un enfoque más integrado usando :

(function($){ 
    $.extend({ 
     // Case insensative $.inArray (http://api.jquery.com/jquery.inarray/) 
     // $.inArrayIn(value, array [, fromIndex]) 
     // value (type: String) 
     // The value to search for 
     // array (type: Array) 
     // An array through which to search. 
     // fromIndex (type: Number) 
     // The index of the array at which to begin the search. 
     // The default is 0, which will search the whole array. 
     inArrayIn: function(elem, arr, i){ 
      // not looking for a string anyways, use default method 
      if (typeof elem !== 'string'){ 
       return $.inArray.apply(this, arguments); 
      } 
      // confirm array is populated 
      if (arr){ 
       var len = arr.length; 
        i = i ? (i < 0 ? Math.max(0, len + i) : i) : 0; 
       elem = elem.toLowerCase(); 
       for (; i < len; i++){ 
        if (i in arr && arr[i].toLowerCase() == elem){ 
         return i; 
        } 
       } 
      } 
      // stick with inArray/indexOf and return -1 on no match 
      return -1; 
     } 
    }); 
})(jQuery); 
+1

+1 Muy útil, y debería ser la respuesta seleccionada. –

+0

esto debería agregarse a la API de jQuery, copiar y pegar cada vez sería difícil, bien de todos modos – Bor

+0

Esto es asombroso. Solo necesita un corsé derecho al comienzo de la última línea. – EthR

Cuestiones relacionadas