I have the object equis
, and suppose I want the valueequis.valorFantasma
But I don't know if the property exists valorFantasma
, how do I validate that it exists before taking its value?
function funcion(){
//alert('boton presionado');
var existePropiedadFantasma = false;
var equis;
existePropiedadFantasma = typeof equis.propiedadFantasma !== 'undefined';//equis.propiedadFantasma ? true:false;
alert(existePropiedadFantasma ? "Si existe": "No Existe");
}
<input type='button' onclick="funcion()" value='Obtener Valor'/>
I hope you can help me. Thanks.
ZIUL... I tried your answer and I get the same error:
Any example that works?
You must take into account that your variable
equis
is aundefined
when declaring it. You could also use the hasOwnProperty method to check for the existence of a property.Result:
Use
hasOwnProperty()
to check properties of the object,in
for properties inherited from the prototype.Simple example for object properties
Example for checking inherited properties
It is important to keep in mind that an object can have properties and functions, the following example illustrates how to properly validate an object:
The most complete way to do it would be:
This works even if it is an invented inline property, example:
Or if it is a property that can never take the value
null
,0
or''
it can be validated like this:You can use
A simple solution is