Split Property of the JS

Asked

Viewed 119 times

0

I am doing some tests with arrays and functions, in case I want the program to look for a name that is in the names array. The routine even works , but the console shows an error in Slip and if the String name value is not found, it cannot display the console.log at the end.

The error that appears is this: "Error: Typeerror: Unable to get Property 'split' of Undefined or null Reference "

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Buscas com JS</title>
    <link rel="stylesheet" href="">
</head>
<body>
    <input type="text" name="nome" id="buscaNome">
    <button onclick="ProcurarNome()">Buscar</button>
    <p id="msg"></p>


    <script type="text/javascript">
    // PROJETO DE LISTA DE CONTATOS COM BUSCA E EXCLUSÃO //

        var nomes = new Array();
        nomes[0] = "Carlos Alberto";
        nomes[1] = "Marcos Gabriel";
            nomes[2] = "Juliana Custodio";
            nomes[3] = "Ana Alice";
            nomes[4] = "Pedro Lucas";

            var contador = 0;

            // para buscar nomes
            function ProcurarNome(){
                        try{
                        var nome1 = document.getElementById('buscaNome').value;
                              if(nome1 == ''){
                                document.getElementById('msg').innerHTML = 'Digite um nome para Buscar';
                        }

                          for (var i = 0; i <= nomes.length; i++) {
                              var ordem  = nomes[i].split(' '); //vai tranformar o nome em um array//

                                  for(var y = 0; y <= ordem.length; y++){
                                 var pesquisa  = ordem.indexOf(nome1); //vai procura o nome//

                            if(pesquisa != -1){                     
                                document.getElementById('msg').innerHTML = "Nome pesquisado: "+nome1+"<br>Nome completo : "+nomes[i];
                                break;
                                  }  
                        }
                      }

                        console.log("O nome : "+nome1+" não esta na lista");
                  }catch(erro){
                              console.log("Erro: "+erro);
                        }  
                  }


    </script> 

</body>
</html>

1 answer

0

You are trying to access a position of the "names" array that does not exist, so it is not possible to do the split.

Change the repeat loops by removing the equal sign =

 for (var i = 0; i < nomes.length; i++) {...}
  • That’s right, thank you Caique

Browser other questions tagged

You are not signed in. Login or sign up in order to post.