开发者

Search multiple arrays for a string and then set a var - jQuery

I'm looking to set a variable based on which array a string exists in.

For example:

var primary   = ["red", blue", "yellow"];
var secondary = ["orange", "purple", "green"];

Then check for "purple" and return that it is in the "secondary" array and assign it to a variable to use later.

jQuery or Javascript is 开发者_如何学编程fine.


Not sure what you wanted to assign to a variable, so I just used alerts to illustrate the result

var plen = primary.length;

var idx = $.inArray( 'purple', primary.concat( secondary ) );

if( idx === -1 ) {
    alert( 'not found' );
} else if( idx < plen ) {
    alert( idx + ' in primary' );
} else {
    alert( (idx - plen) + ' in secondary' );
}

Example: http://jsfiddle.net/S9WL6/


Then you can make it into a reusable function:

function inArrays( val, arr1, arr2 ) {
    var len1 = arr1.length;

    var idx = $.inArray( val, arr1.concat( arr2 ) );

    var ret = {index:idx,array:null};

    if( idx > -1 ) {
        if( idx < len1 ) {
            ret.array = arr1;
        } else {
            ret.array = arr2;
            ret.index -= len1;
        }
    }
    return ret;
}

inArrays( 'purple', primary, secondary );

EDIT: Or make it into a function that can accept a variable number of Arrays.

Example: http://jsfiddle.net/5pZUQ/

var first = ["red", "blue", "yellow"];
var second = ["orange", "purple", "green"];
var third = ["brown", "black", "white"];

function inArrays(val) {
    var arrays = Array.prototype.slice.call(arguments, 1);

    var len = 0;
    var i = 0;

    var idx = $.inArray(val, [].concat.apply([], arrays));

    var ret = {
        index: idx,
        array: null
    };

    if (idx > -1) {
        do {
            ret.array = arrays[i];
            ret.index = idx - len;
            len += arrays[i].length;
            i++;
        } while (idx >= len)       
    }
    return ret;
}

console.log( inArrays('white', first, second, third) );
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜