Convert reduce function to work with IE

半城伤御伤魂 提交于 2019-12-01 08:03:03

问题


Alright, so I had some help a couple months ago with coming up with a solution to keep count of the elements in an array: Loop through multiple array and keep count of each element

This solution worked perfectly for me until I realized that it's using ES6 which is not supported by IE 11. I've tried to convert it to using functions instead of the arrow function so that it'll work across all browsers but am having some issues.

Here is the current code that does not work in IE:

var b = data.reduce((acc, cur) => {
    cur.ProductHandlingTypes.map(({ Name }) => Name).forEach(n => acc[n] = (acc[n] || 0) + 1);
    return acc;
},
{});

If someone could guide me on what needs to be changed here so that it works in IE that would be great!


回答1:


IE 11 doesn't support arrow functions [1], nor destructuring [2], so convert it to ES5 syntax:

var b = data.reduce(function(acc, cur) {
  cur.ProductHandlingTypes
    .map(function(obj) {
      return obj.Name
    })
    .forEach(function(n) {
      return acc[n] = (acc[n] || 0) + 1
    })

  return acc
}, {});

[1] http://caniuse.com/#feat=arrow-functions

[2] http://kangax.github.io/compat-table/es6/#test-destructuring




回答2:


Remove the de-structuring.

cur.ProductHandlingTypes.map((obj) => obj.Name).forEach(...


来源:https://stackoverflow.com/questions/45284711/convert-reduce-function-to-work-with-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!