gtl*_*wig 221 javascript arrays string testing
我有一个字符串数组和一个字符串.我想针对数组值测试此字符串并应用条件结果 - 如果数组包含字符串do"A",否则执行"B".
我怎样才能做到这一点?
Jam*_*ice 397
indexOf
所有数组都有一个方法(Internet Explorer 8及以下版本除外)将返回数组中元素的索引,如果不在数组中,则返回-1:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
Run Code Online (Sandbox Code Playgroud)
如果需要支持旧的IE浏览器,可以使用MDN文章中的代码对此方法进行填充.
fab*_*eal 55
您可以使用此indexOf
方法并使用以下方法"扩展"Array类contains
:
Array.prototype.contains = function(element){
return this.indexOf(element) > -1;
};
Run Code Online (Sandbox Code Playgroud)
结果如下:
["A", "B", "C"].contains("A")
等于 true
["A", "B", "C"].contains("D")
等于 false
Fix*_*ker 26
var stringArray = ["String1", "String2", "String3"];
return (stringArray.indexOf(searchStr) > -1)
Run Code Online (Sandbox Code Playgroud)
创建此函数原型:
Array.prototype.contains = function ( needle ) {
for (i in this) {
if (this[i] == needle) return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下代码在数组x中搜索
if (x.contains('searchedString')) {
// do a
}
else
{
// do b
}
Run Code Online (Sandbox Code Playgroud)
这将为您做到:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle)
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我发现它在Stack Overflow问题JavaScript中相当于PHP的in_array().
归档时间: |
|
查看次数: |
416853 次 |
最近记录: |