如果字符串被其他字符包围,如何使用inArray()在数组元素中查找字符串 [英] how to use inArray() to find string in array element if string is surrounded by other characters

查看:179
本文介绍了如果字符串被其他字符包围,如何使用inArray()在数组元素中查找字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何使用inArray()搜索数组以获取一个值并返回true,即使该值被其他字符包围.这是我的代码(med是我的数组,它进入了med[1-10]):

How would I search an array using inArray() for a value and return true even if that value is surrounded by other characters. Here is the code I have (med is my array, it goes med[1-10]):

alprazolamlog = $.inArray('alprazolam', med) > -1;
xanaxlog = $.inArray('xanax', med) > -1;
if (alprazolamlog==true) {
    $("#xanax").css("display", "block");
} else if (xanaxlog==true) {
    $("#xanax").css("display", "block");
}

如果数组元素是"xanax"或"alprazolam",则返回true.但是,如果用户输入"xanax xr"或"alprazolam er",它将返回false.是否有任何方法可以在该特定数组元素中的任何位置搜索字符串"xanax"或"alprazolam",即使该特定数组元素中还有其他字符,并且在这种情况下还返回true?

It returns true if the array element is "xanax" or "alprazolam". But if a user enters "xanax xr" or "alprazolam er" it will return false. Is there any way to search for string "xanax" or "alprazolam" at any point in that particular array element, even if there are other characters in that particular array element, and to return true in this case?

推荐答案

如果要查找部分匹配项,则不能使用$.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;

这篇关于如果字符串被其他字符包围,如何使用inArray()在数组元素中查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆