Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

FranJun

Buscar posição do Array literal

Recommended Posts

Oi pessoal estou tentando buscar a posição do Array literal com o indexOf() mais ele retorna -1, será que estou fazendo correto?

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the position of the element "Apple":</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var fruits = [{"id": 1, "nome": "Banana"}, {"id": 1, "nome": "Orange"}, {"id": 1, "nome": "Apple"}, {"id": 1, "nome": "Mango"}];
    var a = fruits.indexOf("Orange");
    document.getElementById("demo").innerHTML = a;
}
</script>

<p><b>Note:</b> The indexOf method was introduced in JavaScript 1.6, and does not work in Internet Explorer 8 and earlier versions.</p>

</body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

fonte: http://www.w3schools.com/jsref/jsref_indexof.asp

no seu caso eu faria algo assim

...
function myFunction() {
var fruits = [{"id": 1, "nome": "Banana"}, {"id": 1, "nome": "Orange"}, {"id": 1, "nome": "Apple"}, {"id": 1, "nome": "Mango"}];
for(var i in fruits)
{
      if(fruits[i].nome.indexOf('Orange') >=0)
      {
             //i = indice atual
            document.getElementById("demo").innerHTML = i;
             return false;
      }
}

}
</script>
...

indexOf tbm funciona com a array, mas não sei se vc pode colocar o objeto inteiro na comparacao...

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.