Problem with access to "Undefined" properties

Asked

Viewed 220 times

3

I have a variable that looks for a input and from that she works getting information from her.

The problem I have is that when the input is not there, the script for saying that it cannot access properties of something indefinite: Cannot read Property '0' of Undefined.

How to ignore this or simply make a check for my script don’t stop? In PHP I would do something with isset but in Javascript I have no idea...

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

2 answers

2

You can check if it exists before trying 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 here.

2

I realized that you are using Jquery. This means that the return of the selector will always return one object (one "species" array/Collection), although the selector does not find anything (this is to allow a method chaining). Then I wouldn’t be able to make a comparison with == null or type of === undefined.

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

So you can check whether your dial has returned anything or not by 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; it 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 the methods of a true Array, such as the method join().

(...)

A jQuery object can be empty, containing no element.

Browser other questions tagged

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