[英]Fat arrow usage with map
JavaScript newbie here. JavaScript新手在这里。 While trying to use Arrray.map with fat arrow, I am getting compilation errors.
尝试通过粗箭头使用Arrray.map时,出现编译错误。 Below is my sample code along with the error.
以下是我的示例代码以及错误。
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 works as expected with anonymous function, but gives below error when I use fat arrow instead. Array.map与匿名函数一样可以正常工作,但是当我使用粗箭头时却出现以下错误。
employeesWithOnlyCity = employeesWithComplexLocation.map(e => {
name: e.name,
location: e.location.city
});
SyntaxError: Unexpected token :
The fat arrow works fine with Array.every, or Array.filter. 粗箭头可以与Array.every或Array.filter一起使用。 Not sure what I am missing here with Array.map
不知道我在这里缺少Array.map
The reason your second usage is causing an error is because when using the javascript =>
operator {}
denotes a function body, not an object. 您的第二种用法引起错误的原因是,当使用javascript
=>
运算符{}
表示函数体,而不是对象。 The MDN article on Arrow functions mentions this here and provides a link to a more thorough explaination ( here ) that says this 关于Arrow函数的MDN文章在此处提到了这一点,并提供了指向更详尽的解释( 此处 )的链接,
The rule in ES6 is that { immediately following an arrow is always treated as the start of a block, never the start of an object.
ES6中的规则是{紧跟在箭头之后始终被视为块的起点,而不是对象的起点。
If you need to return an object from an arrow function you should wrap the object in parentheses to let Javascript know not to expect a statement block. 如果需要从箭头函数返回对象,则应将该对象括在括号中,以使Javascript知道不要使用语句块。
var test = e => ({test: e}); document.getElementById("output").innerHTML = JSON.stringify(test("My Value"));
Value: <span id="output">...</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.