What are the differences between Array map and rxjs map

前端 未结 3 2236
误落风尘
误落风尘 2021-02-20 14:07

I was wondering what the map on both rxjs and array works the same way. What are the differences between the uses of both the array map method and rxjs map operator?

3条回答
  •  一个人的身影
    2021-02-20 14:36

    Their functioning is quite the same, they give a new Array / Observable (respectively) with each element transformed according to (usually) a transformation function (the technical computer science name would be a projection), taking as parameter the modified object and its index.

    Array.map is part of the prototype of Array natively. You can use it on any array in any JavaScript environment. (provided you didn't mess up the Array.prototype, of course)

    Observable.map must be imported. (For RxJS 6 : import { map } from 'rxjs/operators';, for older versions : import { map } from 'rxjs/add/operator/map'


    There is a small but significant difference

    Array.map transformation function has access to the whole array being transformed (the third parameter in the projection function).

    Exemple :

         let arr = ['a', 'b', 'c'];
         let arrResult = arr.map(
           (elem, index, wholeArray) => 'element ' + elem + ' was in position ' + index + ' in array ' + wholeArray);
         console.log(arrResult);

    This is "of course" not possible (generally speaking) in the context of Observable since the "whole list" of emitted value is probably not known at the time each element is emitted.


    On the opposite, there is another small difference : Observable.map operator take an (optional) thisArg parameter, so the transformation function has access to some specified context.

    I think this other difference is quite insignificant : Array.map doesn't need this, because it is a function and you can also specify your own "this" with the various ways of calling functions in JavaScript. (I don't find a nice link for this part, anyone who want to add a reference for this in this answer is welcome).

    Also, I would find interesting to be challenged on that last point anyway.

提交回复
热议问题