I l开发者_如何学Pythonove how inarray, searchs an array without looping, but it only does exact/precise matches, where if i used the .match, i can do partial matches, but that requires a loop.
Is there any way to search an array for partial matches, without looping?
There are 2 arrays, 1 to be searched for, the 2nd to replace the text/values if a partial or full match is found in the 1st.
The goal is to have the fastest way to search the array for partial or full matches.
Any suggestions?
Well, .inArray()
of course loops over the Array if Array.prototype.indexOf()
is not available:
snippet
inArray: function( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
snippet
If you just want to know whether or not an entry is contained by an Array, you may just want to .join()
it and use the String.prototype.indexOf()
.
This of course, can't return an index anymore. So you would need to write your own logic. Could be done easily by modifying the above code. For instance:
Array.prototype.ourIndexOf = function(v) {
for ( var i = 0, length = this.length; i < length; i++ ) {
if ( typeof this[i] === 'string' && this[i].indexOf(v) > -1 ) {
return i;
}
}
return -1;
};
['Foobar', 'baseball', 'test123'].ourIndexOf('base') // === 1
Depending on what are you trying to do, you may find some Underscore functions useful:
detect
(returns the first element matching your criteria)select
(returns all matching elements)any
(returns true if any element matches)each
(iterates over elements)map
(transforms an array into a new one)
There are some other functions that you may find useful.
精彩评论