Count of “Defined” Array Elements

后端 未结 7 1557
无人及你
无人及你 2020-12-03 04:30

Given following array:

var arr = [undefined, undefined, 2, 5, undefined, undefined];

I\'d like to get the count of elements which are

相关标签:
7条回答
  • 2020-12-03 05:25

    An array length is not the number of elements in a array, it is the highest index + 1. length property will report correct element count only if there are valid elements in consecutive indices.

    var a = [];
    a[23] = 'foo';
    a.length;  // 24
    

    Saying that, there is no way to exclude undefined elements from count without using any form of a loop.

    0 讨论(0)
提交回复
热议问题