Objects don't have a .length property.
A simple solution if you know you don't have to worry about hasOwnProperty checks, would be to do this:
Object.keys(data).length;
If you have to support IE 8 or lower, you'll have to use a loop, instead:
var length= 0;
for(var key in data) {
if(data.hasOwnProperty(key)){
length++;
}
}
Answer from Cerbrus on Stack OverflowObjects don't have a .length property.
A simple solution if you know you don't have to worry about hasOwnProperty checks, would be to do this:
Object.keys(data).length;
If you have to support IE 8 or lower, you'll have to use a loop, instead:
var length= 0;
for(var key in data) {
if(data.hasOwnProperty(key)){
length++;
}
}
One option is:
Object.keys(myObject).length
Sadly it not works under older IE versions (under 9).
If you need that compatibility, use the painful version:
var key, count = 0;
for(key in myObject) {
if(myObject.hasOwnProperty(key)) {
count++;
}
}
How can I verify if an array is empty or undefined?
Length of Array is returned as undefined
Checking whether an array element is undefined
Create a function to return the length of an array or 0 if a length is not present('undefined', 'string', or 'number'.
If I am accessing an index of an array based on a variable, I would first want to check that the index exists.
My understanding is that if I try to access an index outside of the array's range, I will get a value of 'undefined.' So,
(typeof array[i] === 'undefined')
should return true if array[i] does not exist.
Would it also be possible, because undefined is falsey, to get the same result with
!array[i]
?
Edit: Thanks for the help!
To clarify I am referring to the first question mark, array?.length. I saw this somewhere and can't recall what it does.
const array = [1,2,3] array?.length > 0 ? 'Array contains elements' : 'No elements within array';
Specifically, I want to use the syntax if(arr.length) instead of if(arr.length > 0).
Here's an example of it in function for an Object I'm working on:
name(optStr){ return (arguments.length ? (this._name = optStr) : this._name); } (does set/get)
Edit: I went with this as a general get-set:
field(field, value){
if(value === undefined)
return this[field];
if(Array.isArray(value))
return this[field] = [...value];
return this[field] = value;
}