Count the number of array elements in javascript

Consider the following:

var answers = [];

answers[71] = {
    field: 'value'
};

answers[31] = {
    field: 'value'
};

console.log(answers);

This displays the length of the array as 72 , but I expected it to return 2 . Here's the script output from the chrome console:

enter image description here

Any ideas why this is?

+4
source share
6 answers

You can calculate the actual number of keys with Object.keys(arr).length:

const answers = [];

answers[71] = {
    field: 'value'
};

answers[31] = {
    field: 'value'
};

console.log(Object.keys(answers).length); // prints 2
Run codeHide result
+15
source

By defining index 71, you told the array that it should contain at least 72 entries, and any that you do not explicitly define will contain a value undefined.

, , undefined , , undefined

+2

Array#forEach Array#reduce

var answers = [], count = 0;

answers[71] = { field: 'value' };
answers[31] = { field: 'value' };
answers.forEach(_ => count++);

console.log(count);
console.log(answers.reduce(r => r + 1, 0));
Hide result
+1

Object.keys(your_object_like_array).length

.

+1

Array#filter , undefined.

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);
Hide result
+1

, ?

.

MDN:

length 32- , .

spec:

, , , , length , , , ;

, , . ,

answers[71] = {field: 'value'};
answers[31] = {field: 'value'};

72,

delete answers[71];

72, - 32.

, , . , , , , in:

let count = 0;
for (let i = 0; i < arr.length; i++) count += i in arr;
+1

Source: https://habr.com/ru/post/1654049/


All Articles