且构网

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

如何在 JavaScript/jQuery 中查找数组是否包含特定字符串?

更新时间:2023-08-26 12:13:04

你真的不需要 jQuery.

var myarr = ["I", "like", "turtles"];var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

提示:indexOf 返回一个数字,表示指定搜索值第一次出现的位置,如果没有出现则为-1发生

function arrayContains(needle, arrhaystack){返回 (arrhaystack.indexOf(needle) > -1);}

值得注意的是 array.indexOf(..)IE 不支持 <9,但 jQuery 的 indexOf(...) 函数即使对于那些旧版本也能工作.

Can someone tell me how to detect if "specialword" appears in an array? Example:

categories: [
    "specialword"
    "word1"
    "word2"
]

You really don't need jQuery for this.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs

or

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.