Count of “Defined” Array Elements

后端 未结 7 1592
无人及你
无人及你 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:03

    No, the only way to know how many elements are not undefined is to loop through and count them. That doesn't mean you have to write the loop, though, just that something, somewhere has to do it. (See #3 below for why I added that caveat.)

    How you loop through and count them is up to you. There are lots of ways:

    1. A standard for loop from 0 to arr.length - 1 (inclusive).
    2. A for..in loop provided you take correct safeguards.
    3. Any of several of the new array features from ECMAScript5 (provided you're using a JavaScript engine that supports them, or you've included an ES5 shim, as they're all shim-able), like some, filter, or reduce, passing in an appropriate function. This is handy not only because you don't have to explicitly write the loop, but because using these features gives the JavaScript engine the opportunity to optimize the loop it does internally in various ways. (Whether it actually does will vary on the engine.)

    ...but it all amounts to looping, either explicitly or (in the case of the new array features) implicitly.

提交回复
热议问题