简体   繁体   English

适用于Chrome v41和ie11的Java中的意外令牌=>

[英]Unexpected token => in Javascript for chrome v41 and ie11

What is the quick way to fix the error 解决错误的快速方法是什么

Unexpected token => . 意外令牌=>。

I wrote below code and it only runs in higher version of chrome but not on lower version and ie11. 我在下面的代码中编写了代码,它只能在chrome的较高版本中运行,而不能在较低版本的ie11中运行。

var result = aIndice.filter(obj => {
        return obj.Type === "E"
})

You are using an arrow function obj => { } which will not work in Internet Explorer 11. You need to either use tools like Babel to compile your ES6 code to ES5, or simply avoid using any modern features. 您使用的箭头功能obj => { }在Internet Explorer 11中不起作用。您需要使用Babel之类的工具将ES6代码编译为ES5,或者只是避免使用任何现代功能。

You can also write your function like this: 您还可以这样编写函数:

var result = aIndice.filter(function(obj) {
    return obj.Type === "E"
})

Arrow functions are an es2015 feature, therefore they will not run on older browsers. 箭头功能是es2015的功能,因此它们将无法在较旧的浏览器上运行。 Some features can be implemented by using different polyfills like modernizr , but arrow functions are a language expression and thus can't be polyfilled. 某些功能可以通过使用不同的polyfill来实现,例如modernizr ,但是箭头功能是一种语言表达,因此无法进行polyfill。 You can tell what features are available in what browsers by using caniuse . 您可以使用caniuse判断哪些浏览器提供了哪些功能。

The solution to this problem is transpiling the code with a tool like babel . 解决此问题的方法是使用babel之类的工具来编译代码。 To transpile your script with babel, you will need to install npm and node.js , and then initiate an npm project: 要使用babel转换脚本,您需要安装npm和node.js ,然后启动一个npm项目:

$ npm init 

And install the dependencies we need, the babel-cli and a preset for it to use babel-preset-env . 并安装我们需要的依赖项, babel-cli和一个预设,以使用babel-preset-env

$ npm install --save-dev babel-cli babel-preset-env

Now you need a settings file for babel, you can define your target browsers there using browserlist, so create a file named ".babelrc" and in it write: 现在,您需要babel的设置文件,您可以在其中使用browserlist定义目标浏览器,因此创建一个名为“ .babelrc”的文件,并在其中写入:

{
  "presets": [
    ["env", {
      "targets": {
        "ie": "11",
        "chrome": 41
      }
    }]
  ]
}

Add a new npm script to package.json (created by calling npm init) "script.js" is the source script, and "script-transpiled.js" is the output script. 向package.json(通过调用npm init创建)中添加一个新的npm脚本,“ script.js”是源脚本,而“ script-transpiled.js”是输出脚本。

"scripts": {
  "transpile": "babel script.js --o script-transpiled.js"
}

And call 并致电

npm run transpile

Now your script will be transpiled into a new file script-transpiled.js and you can run it the targeted browsers. 现在,您的脚本将被转换为新文件script-transpiled.js ,您可以在目标浏览器中运行它。 To work with a large scale project it is recommended to use babel-loader with webpack . 要处理大型项目,建议将babel-loaderwebpack一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM