Can I use the "card" as a substitute for "for each" / "for"?

For a while, javascript now has a "map" function to iterate over arrays.

It seems possible to use it as a "foreach" statement, for example:

fruitbowl.map(function(fruit){ ... do stuff with fruit }) 

It's better or worse than talking

 for(var i in fruitbowl){ ... do stuff with fruitbowl[i] } 

Saves the need to use an index, but adds a callback; it does not seem very common, so I hesitate to use it, but still want to.

+4
source share
5 answers

The three methods you mentioned have different goals.

The purpose of the Array.prototype.map method is to create a new array with the results of calling the callback function for each element of the array.

The purpose of the Array.prototype.forEach method is to Array.prototype.forEach over an array by executing the provided callback function once for an array element.

The purpose of the for...in statement is to list the properties of an object.

It seems to me that you should avoid the for...in operator for...in order to traverse any array-like object 1 where the real goal is to iterate over the numerical indices, rather than enumerate the properties of the object (even knowing that these indices are properties).

Reasons to avoid for...in for iterating objects that look like an array:

  • Iterating over inherited user-defined properties in addition to array elements, if you use, for example, a library such as MooTools that extend the Array.prototype object, you will see all these extended properties.
  • The iteration order is arbitrary, the elements cannot be visited in numerical order.

Take a look at this article:


1 By objects like an array, I mean any object that contains sequential numeric properties, and the length property

+7
source

This use is considered valid, but a bad style uses the display operation only for its side effects.

+3
source

Readability is worth a lot. The card may confuse those who have never seen it used in this way. This violates the "principle of least surprise."

+1
source

Perl uses a map in a similar, but more natural way.

My rule of thumb is that if it cannot be read better than a loop, then do not use it. It’s hard to debug. But for certain functions, a map is more natural than a loop. If you need to scratch your head - do not do this. Sorry for the guy who follows you, including yourself sometime from now on!

+1
source

Do not use map for your side effects. If your task iterates over an array to do something with each object, use foreach . If you match values, for example. avoiding an array of strings, use map . There is nothing better than clarity and a programmer striving to be smart.

+1
source

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


All Articles