您可以创建一个简单的函数,并将其添加到
Array
原型中(以便可以在任何数组上调用),该函数搜索数组以查找子字符串匹配项:
JSFIDDLE
Array.prototype.containsSubString = function( text ){
for ( var i = 0; i < this.length; ++i )
{
if ( this[i].toString().indexOf( text ) != -1 )
return i;
}
return -1;
}
然后只需在您的数组上使用它:
var array1 = ['12345', '78273', '34784'],
array2 = ['JJJJJ', 'ABCDEF', 'FFDDFF'];
if( array1.containsSubString( 234 ) !== -1)
{
alert("Found in Array1!");
}
if( array2.containsSubString( 'DD' ) !== -1)
{
alert("Found! in Array2");
}
编辑
如果你想查找一个数组中是否有一个元素是另一个字符串的子串,则:
JSFIDDLE
Array.prototype.hasSubStringOf = function( text ){
for ( var i = 0; i < this.length; ++i )
{
if ( text.toString().indexOf( this[i].toString() ) != -1 )
return i;
}
return -1;
}
var array3 = [ 'AB11' ];
if( array3.hasSubStringOf( 'AB11HA' ) !== -1)
{
alert("Array3 contains substring");
}
编辑2
只需将前面的两个函数结合起来:
JSFIDDLE
Array.prototype.containsSubStringOrHasSubstringOf = function( text ){
for ( var i = 0; i < this.length; ++i )
{
if ( this[i].toString().indexOf( text.toString() ) != -1
|| text.toString().indexOf( this[i].toString() ) != -1 )
return i;
}
return -1;
}
var testArrays = [
['BA11ABC', 'BAGL156DC14', 'BA15HC'],
['GL156DC', 'GL166DC', 'GL31BA11AB'],
['BA11', 'BA14', 'BA15'],
['GL156', 'GL24', 'GL31']
],
testValues = [ "BA11AB", "BA15HB", "GL156DC" ],
results = [ 'Results:' ];
var test = function( str, arr ){
var i = arr.containsSubStringOrHasSubstringOf( str );
if ( i !== -1 )
results.push( JSON.stringify( arr ) + ' matches ' + str + ' on ' + arr[i] );
else
results.push( JSON.stringify( arr ) + ' does not match ' + str );
};
for ( var i = 0; i < testArrays.length; ++i )
for ( var j = 0; j < testValues.length; ++j )
test( testValues[j], testArrays[i] );
alert( results.join('\n') );
indexOf
方法。 - elclanrs