Error in JavaScript code

4

I have a code snippet that looks in a Json field called campo , and inserts it into an array, which can not have repeated values. My array always returned undefined and it took me a while to find the error.
Why does JS and even IDE consider this valid? If campo is an array, then it is obvious that after . would call a method. There was no error in the browser.

Wrong code snippet:

while (i < listaContatos.length) {
   var dados = listaContatos[i].dados;
   for (var j = 0; j < dados.length; j++) {
       var nomeCampo = dados[j].campo;
       console.log(nomeCampo);
       if (campos.indexOf <= -1) {
           campos.push(nomeCampo);
         }
      }
   i++;
}
    
asked by anonymous 29.07.2015 / 16:41

2 answers

8

It is not considered an error for some reasons.

  • The dot does not indicate that the method will be called, because for the call of a function the parentheses are mandatory. Otherwise you're just referencing the function as a variable. This makes the code valid because you are comparing a variable of type function with a variable of type number and JavaScript does not restrict it because of its poorly typed nature. In this case, the comparison will always return% with%
  • Second, if it is an array, dot notation can be used to refer to array indexes.
  • For example:

    var meuArray = [];
    meuArray['asd'] = 4;
    console.log(meuArray.asd); // 4
    

    It's perfectly possible to override the behavior of false and make that snippet of code work in an interesting way:

    var meuArray = [];
    meuArray['indexOf'] = -5;
    console.log(meuArray.indexOf <= -1); // true
    meuArray['indexOf'] = 5;
    console.log(meuArray.indexOf <= -1); // false
    
        
    29.07.2015 / 19:26
    2
    campos.indexOf <= -1
    

    When performing this comparison, you are comparing a function ("fields.indexOf") with an integer "-1". The comparison is valid since "indexOf" is an attribute of the Array object, although it is a function, but could be an integer as the "length" attribute.

        
    29.07.2015 / 16:50