2013-01-22 105 views
5

如果我有一個days names的數組,我想檢查例如sunday - 首字母大寫還是小數字 - 在這個數組中,最好的辦法是什麼?檢查數組中的字符串javascript

+1

[array.contains(obj)in JavaScript]的重複可能性(http://stackoverflow.com/questions/237104/array-containsobj-in-javascript) –

回答

19

你也可以使用Array.indexOf

var days = ["monday", 
      "tuesday", 
      "wednesday", 
      "thursday", 
      "friday", 
      "saturday", 
      "sunday"]; 

function isInArray(days, day) { 
    return days.indexOf(day.toLowerCase()) > -1; 
} 

isInArray(days, "Sunday"); // true 
isInArray(days, "sunday"); // true 
isInArray(days, "sUnDaY"); // true 
isInArray(days, "Anyday"); // false 

檢查MDN瀏覽器的兼容性。

4
function is_in_array(s,your_array) { 
    for (var i = 0; i < your_array.length; i++) { 
     if (your_array[i].toLowerCase() === s.toLowerCase()) return true; 
    } 
    return false; 
} 

用法:

var arr = ["hello","ToTo"]; 
is_in_array("toto",arr) //true 
is_in_array("todto",arr) //false