How to determine the number of specific elements in an array?

If I have an array in Javascript that has been populated sporadically, how can I determine the number of elements without anything in the array?

eg:

var zipCodes = [];
zipCodes[10006] = 'New York, NY';
zipCodes[90210] = 'Los Angeles, CA';

zipCodes.length returns 90,211 here, and I really don't want to iterate over 90,209 draws to find out that I have two valid elements. Using a for-in loop means accessing everything that can create a bubble between the prototype chain and trying to figure out if this is part of this array.

Is there any way, given the array given above, I can extract "2" as the number of specific elements?

+3
source share
2 answers

- ( /-):

var zipCodes = {};
zipCodes[10006] = 'New York, NY';
zipCodes[90210] = 'Los Angeles, CA';


for(var zipCode in zipCodes) {
    if(zipCodes.hasOwnProperty(zipCode)) {//makes sure prototypes aren't taken into account

    }
}

: :

var zipCodes = [];
zipCodes.push({10006:'New York, NY'});
zipCodes.push({90210: 'Los Angeles, CA'});

//zipCodes.length = 2

+12

( ) , (?) .

, , , :

var indexesNext = 0;
var indexes = new Array();
for(i = 0 ; i < zipCodes.length ; i++) 
     if(zipCodes[i] != null) indexes[indexesNext++] = i;

zipCodes , , .

sort() Javascript , . , (YMMV , Javascript- FFX 3.1 Chrome, , , .)

0

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


All Articles