Convert reduce function to work with IE

2019-03-04 06:37发布

问题:

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(...