Como descobrir se um array contém uma string específica em JavaScript/jQuery?

Alguém pode me dizer como detectar se "palavra especial" aparece em um array? Exemplo:

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

jQuery oferece $.inArray:

Note que o inArray retorna o índice do elemento encontrado, então 0 indica que o elemento é o primeiro no array. O -1 indica que o elemento não foi encontrado.

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>

Editar 3,5 anos depois

O $.inArray é efetivamente um wrapper para o Array.prototype.indexOf em navegadores que o suportam (quase todos eles hoje em dia), enquanto fornece um calço naqueles que não't. É essencialmente equivalente a adicionar um calço ao `Array.prototype', que é uma forma mais idiomática/JSish de fazer as coisas. MDN fornece tal código. Hoje em dia eu tomaria esta opção, ao invés de usar o wrapper jQuery.

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

Editar mais 3 anos depois

Gosh, 6,5 anos?!

A melhor opção para isso no Javascript moderno é "Array.prototype.includes":

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

Sem comparações e sem resultados confusos `-1'. Ele faz o que queremos: ele retorna "verdadeiro" ou "falso". Para navegadores antigos ele's polyfillable usando o código no MDN.

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

var foundPresent = categoriesPresent.includes('specialword');
var foundNotPresent = categoriesNotPresent.includes('specialword');

console.log(foundPresent, foundNotPresent); // true false
Comentários (22)

Aqui tem:

$.inArray('specialword', arr)

Esta função retorna um inteiro positivo (o índice do array do valor dado), ou -1 se o valor dado não foi encontrado no array.

Demotação em directo: http://jsfiddle.net/simevidas/5Gdfc/

Provavelmente queres usar isto dessa maneira:

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

Você pode utilizar um laço "para":

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