Iterate over specific elements of a JS array

I am using a JS array for map identifiers for actual elements, i.e. for a keystore. I would like to go through all the elements. I tried several methods, but everyone has their caveats:

for (var item in map) {...}

Iterates over all the properties of an array, so it will also include functions and extensions for Array.prototype. For example, someone in the Prototype library will slow down existing code in the future.

var length = map.lenth;
for (var i = 0; i < length; i++) {
  var item = map[i];
  ...
}

works but just how

$.each(map, function(index, item) {...});

They iterate over the entire range of indexes 0..max (id), which has terrible flaws:

var x = [];
x[1]=1;
x[10]=10;
$.each(x, function(i,v) {console.log(i+": "+v);});

0: undefined
1: 1
2: undefined
3: undefined
4: undefined
5: undefined
6: undefined
7: undefined
8: undefined
9: undefined
10: 10

, . , , undefined . ( , IE)?

+3
7

hasOwnProperty for ... in, , :

for (var item in map)
  if (map.hasOwnProperty(item)) {
    // do something
  }
+4

:

- -, :

var map = {};
map[123] = 'something';
map.foo = 'bar';
// same as map['foo'] = 'bar';
//...

, . 123. obj.key ( - 123 , ) obj['key'] .

, .

hasOwnProperty ( , for...in):

for(var key in obj) {
    if(obj.hasOwnProperty(key)) {
        //do something
    }
}

, ( false) .

+4

1) , , , , .

2), - -

for(var i, len = arr.length;len < i;i++)

.

3) $.each , - , .

+2

EcmaScript 5 Object.keys , ES5, :

Object.keys = function (o) {
  var keys = [];
  var hasOwnProp = Object.prototype.hasOwnProperty;
  if (Object.prototype.toString.call(o) === '[object Array]') {
    for (var k in o) {
      if (+k === (k & 0x7fffffff) && hasOwnProp.call(o, k)) {
        keys[keys.length] = k;
      }
    }
    keys.sort(keys, function (a, b) { return a - b; });
  } else {
    for (var k in o) {
      if (hasOwnProp.call(o, k)) {
        keys[keys.length] = k;
      }
    }
  }
  return keys;
};
+2

.

var map = {};
map[key] = value;
...
for (var key in map) {
   do something to map[key]
}
0

, , , undefined, a b. , , undefined:

x = $.grep(x, function(v, i) { return (typeof(v) != "undefined"); });
0

No. The only way would be to completely exclude items from the collection, any solution you came up with would still have to run a test for each item for the value.

You can come up with different ways to add the keys / values ​​of elements to object literals or whatever you have, but you still need to omit undefined entries if you don't want to list them.

-1
source

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


All Articles