且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果字符串被其他字符包围,如何使用inArray()在数组元素中查找字符串

更新时间:2023-11-06 23:19:40

如果要查找部分匹配项,则不能使用$.inArray().就是那样行不通.取而代之的是,您可以自己迭代数组,然后对所需的每个数组元素进行任何类型的匹配.

You can't use $.inArray() if you're looking for a partial match. It just doesn't work that way. Instead, you can just iterate the array yourself and do whatever kind of match against each element of the array that you want.

$.inArray()没有魔力.这只是在数组中查找精确值的捷径,但是如果该捷径不完全是您想要的,则只需进行自己的迭代和自己的比较类型即可.

There's no magic to $.inArray(). It's just a shortcut for finding an exact value in an array, but if that shortcut isn't exactly what you want, then just do your own iteration and your own type of comparison.

例如:

function findPartialStrInArray(array, target) {
    for (var i = 0; i < array.length; i++) {
        var item = array[i];
        // if this array element is a string and contains the target string
        if (typeof item === "string" && item.indexOf(target) !== -1) {
            return i;
        }
    }
    return -1;
}

var alprazolamlog = findPartialStrInArray(med, 'alprazolam') > -1;
var xanaxlog = findPartialStrInArray(med, 'xanax') > -1;