开发者

Alternative to jquery .inarray?

开发者 https://www.devze.com 2023-02-12 06:56 出处:网络
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.

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:

  1. detect (returns the first element matching your criteria)
  2. select (returns all matching elements)
  3. any (returns true if any element matches)
  4. each (iterates over elements)
  5. map (transforms an array into a new one)

There are some other functions that you may find useful.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号