2010-08-02 7 views

답변

23

당신은 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

"return false;"를 추가 할 수 있습니다. if 문 끝에서 일치하는 요소가 발견 된 후에 'each'가 계속되지 않습니다. (jQuery.each()에서 "return false;"는 일반 JavaScript 루프에서 "break;"와 동일합니다. –

+3

Lower가 아닌 LOWCase가 아닌가요? – Sarfraz

+0

@Jordan and @Sarfraz : 두 좋은 점 –

1

아니요. 데이터를 조작해야합니다. 보통 쉽게 비교할 수 있도록 모든 문자열을 소문자로 만듭니다. 또한 대소 문자를 구분하지 않기 위해 필요한 변환을 수행하는 사용자 지정 비교 함수를 사용할 수도 있습니다.

1

배열을 통해 각 요소 tolower를 당신이 찾고있는 tolower를하지만, 그 시점에서 루프, 당신은뿐만 아니라 단지 대신 inArray를 사용하여 비교할 수있다 수()

1

독자적인 솔루션을 구현해야하는 것처럼 보입니다. Here은 jQuery에 사용자 정의 함수를 추가하는 좋은 방법입니다. 당신은 단지 데이터를 반복하고 정규화 한 다음 비교할 사용자 정의 함수를 작성해야합니다.

4

@Drew Wills에 감사드립니다. 나는이 같은 작업을 위해 underscore를 사용하는 것을 선호

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

이것은 나를 위해 완벽하게 작동했습니다. – Alan

1

요즘 :

나는이로 재 작성

: 경우 사람이 를 사용하여보다 통합 된 접근 방식을 원
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

에서

(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 매우 유용하며 선택한 대답이어야합니다. –

+0

jQuery API에이 코드를 추가해야합니다. 복사 할 때마다 붙여 넣기가 어쨌든 어려울 것입니다. – Bor

+0

정말 멋지 네요. 마지막 줄 시작 부분에 오른쪽 중괄호가 필요합니다. – EthR

관련 문제