我有一个字符串数组和一个字符串,我想将该字符串与数组值进行比较,并对结果应用条件 - 如果数组包含该字符串则执行"A",否则执行"B"。如何实现这个功能?
includes
函数,这正是作者所要求的。以下是一个例子:['A', 'B'].includes('A') // >> true
['A', 'B'].includes('C') // >> false - Stanislau BaranouskiindexOf
方法,并像这样 "扩展" Array 类的方法 contains
:Array.prototype.contains = function(element){
return this.indexOf(element) > -1;
};
以下是结果:
["A", "B", "C"].contains("A")
相等于 true
["A", "B", "C"].contains("D")
相等于 false
var stringArray = ["String1", "String2", "String3"];
return (stringArray.indexOf(searchStr) > -1)
Array.prototype.contains = function ( needle ) {
for (var i in this) { // Loop through every item in array
if (this[i] == needle) return true; // return true if current item == needle
}
return false;
}
if (x.contains('searchedString')) {
// do a
}
else
{
// do b
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle)
return true;
}
return false;
}
我在Stack Overflow的问题中发现了这个内容,问题链接为JavaScript equivalent of PHP's in_array()。