Consider the following:
var answers = [];
answers[71] = {
field: 'value'
};
answers[31] = {
field: 'value'
};
console.log(answers);
This outputs the length of the array as 72 but I was expecting it to return 2. Here's the output of the script from chrome console:
Any ideas why this is?
You can count the actual number of keys using Object.keys(array).length
:
const answers = [];
answers[71] = {
field: 'value'
};
answers[31] = {
field: 'value'
};
console.log(Object.keys(answers).length); // prints 2
You can simply use Array#filter
method which doesn't iterate over deleted or undefined array elements.
answers.filter(function(v){ return true; }).length
var answers = [];
answers[71] = {
field: 'value'
};
answers[31] = {
field: 'value'
};
console.log(answers.filter(function(v) {
return true;
}).length);
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