| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf | [Back] [Original] |
Get to know MDN better
Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade MDN Web Docs.
This feature is well established and works across many devices and browser versions. Its been available across browsers since julho de 2015.
O mtodo indexOf() retorna o primeiro ndice em que o elemento pode ser encontrado no array, retorna -1 caso o mesmo no esteja presente.
const beasts = ["ant", "bison", "camel", "duck", "bison"];
console.log(beasts.indexOf("bison"));
// Expected output: 1
// Start from index 2
console.log(beasts.indexOf("bison", 2));
// Expected output: 4
console.log(beasts.indexOf("giraffe"));
// Expected output: -1
array.indexOf(elementoDePesquisa, [pontoInicial = 0])
elementoDePesquisaElemento a ser pesquisado no array.
pontoInicialO ndice para iniciar a procura. Se o ndice for maior ou igual ao tamanho do array, retornado -1 e signfica que o item no ser procurado. Se o pontoInicial fornecido com um nmero negativo, tomado como deslocamento da extremidade do array. Nota: se o pontoInicial fornecido negativo, a procura no array acontece de frente para trs. Se o pontoInicial fornecido 0, ento o array inteiro ser pesquisado. Padro: 0 (pesquisa em todo array).
indexOf() compara o elementoDePesquisa com os elementos do Array usando igualdade estrita (o mesmo mtodo usado pelo ===, ou triple-equals operator).
indexOf()O exemplo seguinte usa indexOf() para localizar valores em um array
var array = [2, 5, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
var indices = [];
var array = ["a", "b", "a", "c", "a", "d"];
var elemento = "a";
var idx = array.indexOf(elemento);
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(elemento, idx + 1);
}
console.log(indices);
// [0, 2, 4]
function atualizarColecaoVegetais(vegetais, vegetal) {
if (vegetais.indexOf(vegetal) === -1) {
vegetais.push(vegetal);
console.log("Nova coleo de vegetais : " + vegetais);
} else if (vegetais.indexOf(vegetal) > -1) {
console.log(vegetal + " j existe na coleo de vegetais.");
}
}
var vegetais = ["batata", "tomate", "pimenta", "pimentao"];
atualizarColecaoVegetais(vegetais, "espinafre");
// Nova coleo de vegatais : batata,tomate,pimenta,pimentao,espinafre
atualizarColecaoVegetais(vegetais, "espinafre");
// espinafre j existe na coleo de vegetais.
indexOf() foi adicionado ao ECMA-262 standard em sua 5 edio; como tal, no pode estar presente em todos navegadores.Voc pode contornar isso utilizando o seguinte codigo no inicio de seus scripts. Isto permitir que voce use o indexOf() quando no possuir suporte nativo. Esse algoritmo corresponde ao especificado no ECMA-262, edio 5, assumindo TypeError e Math.abs() tem seus valores originais.
// Passos para a produo do ECMA-262, Edition 5, 15.4.4.14
// Referncia: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elementoDePesquisa, pontoInicial) {
var k;
//1. Deixe-o ser o resultado da chamada de toObject
// passando o valor de this como argumento.
if (this == null) {
throw new TypeError(
'"this" nulo (null) ou no foi definido (undefined)',
);
}
var O = Object(this);
// 2. Deixar o tamanhoValor ser o resultado da
// chamada do mtodo interno Get de 0 com o
// argumento "length"
// 3. Deixar o tamanhoValor ser um ToUint32(tamanhoValor).
var tamanho = O.length >>> 0;
// 4. se o tamanho 0, retorna -1.
if (tamanho === 0) {
return -1;
}
// 5. Se o argumento pontoInicial for passado,
// use o ToInteger(pontoInicial); senao use 0.
var n = +pontoInicial || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
//6. Se n >= tamanho, retorna -1.
if (n >= tamanho) {
return -1;
}
// 7. Se n>= 0, entao k seja n.
// 8. Senao, n<0, k seja tamanho - abs(n).
// Se k menor que 0, entao k seja 0.
k = Math.max(n >= 0 ? n : tamanho - Math.abs(n), 0);
// 9. Repita, enquanto k < tamanho
while (k < tamanho) {
// a. Deixe Pk ser ToString(k).
// isto implicito para operandos LHS de um operador
// b. Deixe o kPresent ser o resultado da chamada do mtodo
// interno de 0 com argumento Pk
// Este passo pode ser combinado com c.
// c. Se kPresent true, entao
// i. Deixe o elementK ser o resultado da chamada do metodo
// interno Get de 0 com argumento ToString(k)
// ii. Deixe o resultado ser aplicado pelo Algoritmo de
// Comparao de Igualdade Estrita (Strict Equality Comparison)
// para o elementoDePesquisa e elementK
// iii. caso verdadeiro, retorne k.
if (k in O && O[k] === elementoDePesquisa) {
return k;
}
k++;
}
return -1;
};
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-array.prototype.indexof |
This page was last modified on 22 de mai. de 2026 by MDN contributors.
ArrayArray.prototype.at()Array.prototype.concat()Array.prototype.copyWithin()Array.prototype.entries()Array.prototype.every()Array.prototype.fill()Array.prototype.filter()Array.prototype.find()Array.prototype.findIndex()findLast()findLastIndex()Array.prototype.flat()Array.prototype.flatMap()Array.prototype.forEach()Array.prototype.includes()Array.prototype.indexOf()Array.prototype.join()Array.prototype.keys()Array.prototype.lastIndexOf()Array.prototype.map()Array.prototype.pop()Array.prototype.push()Array.prototype.reduce()Array.prototype.reduceRight()Array.prototype.reverse()Array.prototype.shift()Array.prototype.slice()Array.prototype.some()Array.prototype.sort()Array.prototype.splice()Array.prototype.toLocaleString()toReversed()toSorted()toSpliced()Array.prototype.toString()Array.prototype.unshift()Array.prototype.values()with()Array.prototype[@@iterator]()Object/FunctionObject.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |