有人能告诉我如何检测“特殊词”出现在数组中吗?例子:

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

当前回答

给你:

$.inArray('specialword', arr)

该函数返回一个正整数(给定值的数组下标),如果在数组中没有找到给定值,则返回-1。

现场演示:http://jsfiddle.net/simevidas/5Gdfc/

你可能会这样使用它:

if ( $.inArray('specialword', arr) > -1 ) {
    // the value is in the array
}

其他回答

你可以使用for循环:

var found = false;
for (var i = 0; i < categories.length && !found; i++) {
  if (categories[i] === "specialword") {
    found = true;
    break;
  }
}

我不喜欢$. inarray(..),这是一种丑陋的、类似jquery的解决方案,大多数理智的人都不会容忍。下面是一个片段,它添加了一个简单的contains(str)方法到你的武器库:

$.fn.contains = function (target) {
  var result = null;
  $(this).each(function (index, item) {
    if (item === target) {
      result = item;
    }
  });
  return result ? result : false;
}

类似地,您可以对$进行包装。扩展中的inArray:

$.fn.contains = function (target) {
  return ($.inArray(target, this) > -1);
}

jQuery提供了$.inArray:

注意,inArray返回找到的元素的索引,因此0表示该元素是数组中的第一个元素。-1表示没有找到该元素。

var categorespresent = ['word', 'word', 'specialword', 'word']; var categororiesnotpresent = ['word', 'word', 'word']; var foundPresent = $。inArray('specialword', categorespresent) > -1; var foundNotPresent = $。inArray('specialword', categoresnotpresent) > -1; console.log (foundPresent foundNotPresent);// true false < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>


3.5年后编辑

美元。inArray实际上是Array.prototype.indexOf的包装器,在支持它的浏览器中(几乎所有浏览器都支持),而在那些不支持它的浏览器中提供了一个垫片。它本质上等同于向Array添加一个垫片。原型,这是一种更习惯/JSish的做事方式。MDN提供了这样的代码。现在,我会选择这个选项,而不是使用jQuery包装器。

var categorespresent = ['word', 'word', 'specialword', 'word']; var categororiesnotpresent = ['word', 'word', 'word']; var foundPresent = categorespresent . indexof ('specialword') > -1; var foundNotPresent = categororiesnotpresent . indexof ('specialword') > -1; console.log (foundPresent foundNotPresent);// true false


3年后再编辑

天哪,6.5年?

在现代Javascript中,最好的选择是Array.prototype.includes:

var found = categories.includes('specialword');

没有比较,没有令人困惑的-1结果。它做了我们想要的:返回true或false。对于较老的浏览器,可以使用MDN上的代码进行多填充。

var categorespresent = ['word', 'word', 'specialword', 'word']; var categororiesnotpresent = ['word', 'word', 'word']; var foundPresent = categorespresent .includes('特殊词'); var foundNotPresent = categororiesnotpresent .includes('特殊词'); console.log (foundPresent foundNotPresent);// true false

给你:

$.inArray('specialword', arr)

该函数返回一个正整数(给定值的数组下标),如果在数组中没有找到给定值,则返回-1。

现场演示:http://jsfiddle.net/simevidas/5Gdfc/

你可能会这样使用它:

if ( $.inArray('specialword', arr) > -1 ) {
    // the value is in the array
}

你真的不需要jQuery。

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

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

or

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

值得注意的是,在IE < 9中不支持array.indexOf(..),但jQuery的indexOf(…)函数即使在这些旧版本中也可以工作。