what use does the javascript forEach method have (that map can't do)?

前端 未结 8 1455
小鲜肉
小鲜肉 2020-12-04 07:24

The only difference I see in map and foreach is that map is returning an array and forEach is not. However, I don\'t even understand the last line

8条回答
  •  忘掉有多难
    2020-12-04 07:49

    This is a beautiful question with an unexpected answer.

    The following is based on the official description of Array.prototype.map().

    There is nothing that forEach() can do that map() cannot. That is, map() is a strict super-set of forEach().

    Although map() is usually used to create a new array, it may also be used to change the current array. The following example illustrates this:

    var a = [0, 1, 2, 3, 4], mapped = null;
    mapped = a.map(function (x) { a[x] = x*x*x; return x*x; });
    console.log(mapped); // logs [0, 1, 4, 9, 16]  As expected, these are squares.
    console.log(a); // logs [0, 1, 8, 27, 64] These are cubes of the original array!!
    

    In the above example, a was conveniently set such that a[i] === i for i < a.length. Even so, it demonstrates the power of map(), and in particular its ability to change the array on which it is called.

    Note1:
    The official description implies that map() may even change length the array on which it is called! However, I cannot see (a good) reason to do this.

    Note2:
    While map() map is a super-set of forEach(), forEach() should still be used where one desires the change a given array. This makes your intentions clear.

    Hope this helped.

提交回复
热议问题