Error Javascript function

Asked

Viewed 93 times

0

someone could tell me what I’m missing in this function of js?

        alert("Insira o numero a ser pesquisado");
        var num = prompt("Insira um numero: ");

        var array = [2,23,4,56,7];

        function pesquisa(array[], num){
            var achou = false;

            for(var i=0; i < array.length-1;i++){
                if(array[i] == num)
                {
                    achou = true;
                }
            }
             return achou;
        }

        if(pesquisa(array,num) == true)
        {
            alert("o elemento procurado está dentro do array");
        }
        else
        {
            alert("O elemento não está no array");
        }
  • 2

    Beware of the i < array.length-1, the < already corrects the upper limit for the last element. In addition there is no notation array[] in javascript, switch to array only.

  • I don’t understand why the boy’s question was denied....

  • 1

    @Marcelobonifazio I wasn’t the downvoter, But I think the reason I voted against is because people tend to discourage questions like "find the mistake there for me" without any indication that something has been tried (like, which line is the mistake? gave error message or only the result that is wrong? etc).

1 answer

1


on the line:

function pesquisa(array[], num){

modify to:

function pesquisa(array, num) {

and everything will work as expected

  • 1

    "everything will work as expected" not everything, see the comment of @Wakim... This solves the syntax error, but not the semantic error (if the element being searched is the last, the AP code will not find it).

  • yes all the reason... and from what I understand my response was later ... so my vote for @Wakin

Browser other questions tagged

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