将JavaScript ES6函数转换为ES3

时间:2019-04-04 05:08:31

标签: javascript arrays ecmascript-6

我有一个数组,可以使用EcmaScript-6函数成功将其转换为字符串格式。但是,如何使用EcmaScript-3执行此操作?接收端点需要ES3功能。

原始数组:

formdata: [
    1: {name: "gender", value: "F", focus: 0, type: "radio"}
    2: {name: "firstname", value: "empty", focus: 0, type: "text"}
    3: {name: "lastname", value: "empty", focus: 0, type: "text"}
    4: {name: "birthday", value: "empty", focus: 0, type: "text"}
    5: {name: "street", value: "empty", focus: 0, type: "text"}
    6: {name: "streetNo", value: "empty", focus: 0, type: "text"}
]

所需的字符串格式

let formdata = gender.radio|F|0;firstName.text|empty|1;lastName.text|empty|0;street.text|empty|0;houseNumber.text|empty|0;zip.text|empty|0;city.text|empty|0;country.select-one|de|0;birthdate-day.text|empty|0;birthdate-month.text|empty|0;birthdate-year.text|empty|0;email.email|empty|0;code.text|filled_out|0

我使用ES6的工作解决方案:

let res = formdata.map(({name,value,focus,type}) => `${name}.${type}|${value}|${focus}`).join(';')

我对转换为ES3的看法:

var res = formdata.map(({name,value,focus,type}) { 
  ("name" + "." + "type" + "|" + "value" + "focus").join(;)
}

该解决方案显然无法正常工作,而且我不确定它是否为有效的ES3 JavaScript。

谢谢!

1 个答案:

答案 0 :(得分:3)

您的ES3尝试问题:

  • 箭头功能缺少箭头,但它也是语法的ES6补充
  • .join(;)无效的JavaScript。 .join(";")是。
  • ES6中引入了
  • 解构语法
  • .map在ES5中引入
  • 您还需要一个“ |”

所以:

var formdata = [{name: "gender", value: "F", focus: 0, type: "radio"},{name: "firstname", value: "empty", focus: 0, type: "text"},{name: "lastname", value: "empty", focus: 0, type: "text"},    {name: "birthday", value: "empty", focus: 0, type: "text"},{name: "street", value: "empty", focus: 0, type: "text"},{name: "streetNo", value: "empty", focus: 0, type: "text"},];

var arr = [];
for (var i = 0; i < formdata.length; i++) {
    var elem = formdata[i];
    arr.push(elem.name + "." + elem.type + "|" + elem.value + "|" + elem.focus);
}
var str = arr.join(";");

console.log(str);