最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does ES6's Map.forEach iterate with 'value, key' instead of 'key, value&#39

programmeradmin6浏览0评论

As shown on MDN, Map's forEach callback is called with value first, and then key. E.g.:

map.forEach(function(value, key, map) { ... })

Seems like key, value is a lot more mon than value, key. Even the Map constructor expects an array of [key, value] pairs.

As shown on MDN, Map's forEach callback is called with value first, and then key. E.g.:

map.forEach(function(value, key, map) { ... })

Seems like key, value is a lot more mon than value, key. Even the Map constructor expects an array of [key, value] pairs.

Share Improve this question asked Oct 13, 2015 at 19:08 ericsocoericsoco 26.3k31 gold badges101 silver badges129 bronze badges 7
  • 1 I usually need the value only, and would end up writing something like .map(function(_, value) { ... }); – Matteo Tassinari Commented Oct 13, 2015 at 19:11
  • I don't now if it is more 'mon', e.g. docs.angularjs/api/ng/function/angular.forEach – Betty St Commented Oct 13, 2015 at 19:11
  • fyi Array.prototype.amp is described in ECMA-262 Edition 5 ecma-international/ecma-262/5.1/#sec-15.4.4.19 – Andreas Louv Commented Oct 13, 2015 at 19:12
  • 2 I think the reason is that it better aligns with forEach method of the Array. – Sergey Rybalkin Commented Oct 13, 2015 at 19:13
  • 4 This was probably chosen for consistency with Array.prototype.forEach, whose callback function takes its parameters in the order value, index, where map items (obviously) are accessed by key rather than by index. – GOTO 0 Commented Oct 13, 2015 at 19:20
 |  Show 2 more ments

1 Answer 1

Reset to default 16

It's probably just for laziness sake. Most forEach loops will only care about the value itself. By supplying it as the first parameter, you can construct a function that only accepts one parameter:

map.forEach(function (value) { /* do something with value */; })

Instead of

map.forEach(function (unused, value) { /* do something with value */; })

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论