ES 6到ES 5需要帮助修复

问题描述 投票:0回答:4

我有两段代码是ES6,但我需要在课堂上使用ES5。创建ES5中列出的每种方法的最佳方法是什么?我从数组输出这些,并且数组中的每个值都需要在一个新行上。

  1. tools.forEach(tools => console.log(tools));
  2. tools.sort().forEach(tools => console.log(tools));
javascript arrays function ecmascript-6 ecmascript-5
4个回答
2
投票

只需使用function就可以了解它:

tools.forEach(function(tool) {
    console.log(tool);
});

并为另一个添加sort

tools.sort().forEach(function(tool) {
    console.log(tool);
});

请注意,尽管您提供的ES6中存在隐式返回,但实际上并不需要在forEach()循环中使用它,这就是我将其排除在外的原因 - 如果您愿意,可以随意添加它。


1
投票

唯一的区别是=>你可以简单地写它;

tools.forEach(function (tools) {
  return console.log(tools);
});

1
投票

您可以使用此babel编译器将代码示例从ES6转换为ES5

https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=C4exBsGcDpJAnYAKAlNAZggogQwMYAWSoEkABALwB8ZeIAdnOAKbTggDmxYUKKA3EA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.3.4

tools.forEach(tools => console.log(tools));

变为:

tools.forEach(function (tools) {
  return console.log(tools);
});

tools.sort().forEach(tools => console.log(tools));

变为:

tools.sort().forEach(function (tools) {
  return console.log(tools);
});

0
投票

=>替换function

1美分

tools.forEach(tools => console.log(tools));

替换为给定的代码

tools.forEach(function(tools){
    console.log(tools));
});

第2

tools.sort().forEach(tools => console.log(tools));

替换为给定的代码

tools.sort().forEach(function(tools){
    console.log(tools));
});

这是转换ES6 to ES5的链接

© www.soinside.com 2019 - 2024. All rights reserved.