Run in your browser (ES5+)
var propCount = Object.keys(navigator).length;
console.log(propCount); // 0
If you do it for a plain object like that
let obj = {
foo: 'bar',
breaking: 'bad'
}
let propCount = Object.keys(obj).length;
console.log(propCount); // 2
Why does it happen?
Sorry if it might relate to another problem like when Object.keys(obj)
is only counting it for simple objects which do not contain functions/arrays
, but this the 1st time I encountered with it.
And would like to know the reason of it.
keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.
How many properties can an object have JS? Summary. JavaScript objects have two types of properties: data properties and accessor properties.
Object.keys() function returns properties of the object that are directly assigned to it. If you do the following:
console.log(navigator.hasOwnProperty('permissions')); // false
If you want to see properties of navigator do the following:
for(let i in navigator){
console.log(i);
}
It will list all the properties of navigator object because for ... in ... loop includes object's prototype.
That's because most properties of navigator
are set on the Navigator
prototype, which the navigator
instance inherits, and Object.keys
only returns the properties set on the navigator
object itself.
You can get those properties from the prototype with this:
Object.keys(Object.getPrototypeOf(navigator));
On a side note, Firefox has the following properties in the navigator
object itself:
[ "doNotTrack", "mozPay", "mozContacts", "mozApps" ]
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