2010-08-02 6 views

Répondre

23

Vous pouvez utiliser 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

Vous voulez ajouter un "return false"; à la fin de cette instruction if, le 'each' ne continue pas après la recherche d'un élément correspondant. (Dans jQuery.each() "return false;" est équivalent à "break;" dans une boucle JavaScript régulière.) –

+3

N'est-ce pas toLowerCase plutôt que toLower? – Sarfraz

+0

@Jordan et @Sarfraz: les deux points positifs –

1

Non. Vous devrez manipuler vos données, je fais habituellement toutes mes chaînes en minuscules pour faciliter les comparaisons. Il y a aussi la possibilité d'utiliser une fonction de comparaison personnalisée qui ferait les transformations nécessaires pour rendre le cas de comparaison insensible.

1

pourrait boucle à travers le réseau et toLower chaque élément et toLower ce que vous cherchez, mais à ce moment, vous pouvez tout aussi bien le comparer au lieu d'utiliser InArray()

1

Il semblerait que vous deviez implémenter votre propre solution. Here est un bon article sur l'ajout de fonctions personnalisées à jQuery. Vous aurez juste besoin d'écrire une fonction personnalisée pour boucler et normaliser les données puis les comparer.

4

Merci à @Drew Wills.

Je réécrite comme ceci:

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

Cela a fonctionné parfaitement pour moi. – Alan

1

Ces jours-ci, je préfère utiliser underscore pour des tâches comme ceci:

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

Dans le cas où quelqu'un voulait une approche plus intégrée à l'aide :

(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 Très utile, et devrait être la réponse sélectionnée. –

+0

cela devrait être ajouté à l'API jQuery, copier-coller à chaque fois que ce serait difficile, bien de toute façon – Bor

+0

C'est génial. Il a juste besoin d'une accolade droite au début de la dernière ligne. – EthR