array.find doesn't work with Babel

2019-06-16 09:31发布

问题:

I'm transpiling my ES2015 code using Babel. However it doesn't translate find for Arrays. The following line throws the error TypeError: options.find is not a function

let options = [2,23,4]
options.find(options, x => x < 10)

回答1:

Use babel polyfill.

require("babel/polyfill");

[1, 2, 3].find((x) => x >= 2);
// => 2

See: Polyfill · Babel

Or you can use callback. Array.find(arr, callback)

Array.find([ 1, 2, 3 ], (x) => x >= 2);
// => 2

Array.prototype.find doesn't work in the runtime · Issue #892 · babel/babel



回答2:

Or if you're using ES6 imports already

import 'babel/polyfill';


回答3:

In newer versions it's

import 'babel-polyfill'

source: Babel Docs



回答4:

If you just concatenate your javascript files with Gulp or Grunt, you can add the script before your javascript files: node_modules/babel-polyfill/dist/polyfill.js.

Do not forget to install it: npm i babel-polyfill.