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

谁能告诉我如何检测"specialword"是否出现在一个数组中?例子。

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

jQuery提供[$.inArray][1]。

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

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = $.inArray('specialword', categoriesPresent) > -1;
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;

console.log(foundPresent, foundNotPresent); // true false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = categoriesPresent.indexOf('specialword') > -1;
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;

console.log(foundPresent, foundNotPresent); // true false

3年后再编辑

天哪,6.5年?!

评论(22)

给你。

$.inArray('specialword', arr)

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

实时演示: http://jsfiddle.net/simevidas/5Gdfc/

你可能想这样使用它。

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

你可以使用一个for循环。

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