In JavaScript / jQuery, if I alert
some object, I get either [object]
or [object Object]
Is there any way to know:
what is the difference between these two objects
what type of Object is this
what all properties does this object contains and values of each property
?
We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.
To get all own properties of an object in JavaScript, you can use the Object. getOwnPropertyNames() method. This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument.
An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.
Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.
You can look up an object's keys and values by either invoking JavaScript's native for in
loop:
var obj = { foo: 'bar', base: 'ball' }; for(var key in obj) { alert('key: ' + key + '\n' + 'value: ' + obj[key]); }
or using jQuery's .each()
method:
$.each(obj, function(key, element) { alert('key: ' + key + '\n' + 'value: ' + element); });
With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString
method on an object, like this:
alert(Object.prototype.toString.call([]));
The above will output [object Array]
.
There are several other class names, like [object Object]
, [object Function]
, [object Date]
, [object String]
, [object Number]
, [object Array]
, and [object Regex]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With