Problem with access to undefined properties

3

I have a variable that looks for input and from this it works by getting information from it.

The problem that arises to me is that when the input is not there, the script for saying that it can not access properties of something undefined: Can not read property '0' of undefined .

How can I ignore this or simply do a check so my script does not stop ? In PHP I would do something with isset but in JavaScript I have no idea ...

files = $(".X"); 
if (files[0].files.length >= 1) { 
    //...
}
    
asked by anonymous 28.01.2017 / 15:06

2 answers

2

You can check if it exists before attempting to access it:

files = $(".X"); 
if (files[0]){
  if (files[0].files.length >= 1) { 
    //...
  }
}

if (files[0]) will return true if it does not fall under any of these conditions #

    

28.01.2017 / 15:08
2

I noticed that you are using JQuery. This means that the return of the selector will always return a object (a "sort" of array / collection), even if the selector does not find anything (this happens to allow a method concatenation). Then you would not be able to make a comparison with == null or type of === undefined .

However, in this object, we have the property .length .

Then you can check if your selector has returned something or not checking this property. It would look something like this:

var files = $(".X");

if (files.length > 0) {
    /* seu código */
}

Translating from documentation :

  

The jQuery object behaves like an array; has a property    length and the elements in your object can be accessed by your   numerical indexes [0] to [length-1] . Note that a jQuery object is not   currently a JavaScript Array, so it does not have all methods   of a true Array, such as the join() method.

     

(...)

     

A jQuery object can be empty , containing no element.

    
28.01.2017 / 15:15