JavaScript新手在这里.在尝试使用带有胖箭头的Arrray.map时,我遇到了编译错误.下面是我的示例代码以及错误.
var employeesWithComplexLocation = [{
"name": "jon",
"location": {
"country": "usa",
"city": "austin"
}
}, {
"name": "jane",
"location": {
"country": "usa",
"city": "houston"
}
}, {
"name": "mary",
"location": {
"country": "usa",
"city": "dallas"
}
}];
var employeesWithOnlyCity = employeesWithComplexLocation.map(function(element) {
return {
name: element.name,
location: element.location.city
};
});
console.log(employeesWithOnlyCity);
console.log('Now using fat arrow:')
employeesWithOnlyCity = employeesWithComplexLocation.map(e => {
name: e.name,
location: e.location.city
});
console.log(employeesWithOnlyCity);
Array.map按预期使用匿名函数工作,但是当我使用胖箭头时,会给出以下错误.
employeesWithOnlyCity = employeesWithComplexLocation.map(e => { name: e.name, location: e.location.city }); SyntaxError: Unexpected token :
胖箭头适用于Array.every或Array.filter.不确定我在这里缺少Array.map
第二次使用导致错误的原因是因为使用javascript =>
运算符{}
表示函数体,而不是对象.关于Arrow函数的MDN文章在这里提到了这一点,并提供了一个链接到更详尽的说明(这里)
ES6中的规则是{紧跟箭头后始终被视为块的开始,而不是对象的开始.
如果你需要从箭头函数返回一个对象,你应该将对象包装在括号中,让Javascript知道不要期望一个语句块.
var test = e => ({test: e});
document.getElementById("output").innerHTML = JSON.stringify(test("My Value"));
Value: ...