Javascript 检查数组中的字符串是否javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14461450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:51:40 来源:igfitidea点击:
Check if string inside an array javascript
提问by Yasser Moussa
If i had an array of days namesand i wanted to check for example if sunday- first letter capital or small - in this array what would be the best thing to do ?
如果我有一个数组days names并且我想检查例如sunday- 首字母大写或小写 - 在这个数组中什么是最好的?
回答by VisioN
You may also use Array.indexOf:
您还可以使用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
Check the browser compatibility in MDN.
检查MDN 中的浏览器兼容性。
回答by JohnJohnGa
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;
}
Usage:
用法:
var arr = ["hello","ToTo"];
is_in_array("toto",arr) //true
is_in_array("todto",arr) //false

