如何从JavaScript中的一个划线箭头函数返回匿名对象? [英] How to return anonymous object from one liner arrow function in javascript?

查看:69
本文介绍了如何从JavaScript中的一个划线箭头函数返回匿名对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近切换到es6,并开始在代码中使用箭头功能. 重构时,我遇到了以下代码

I recently switched to es6 and started using arrow functions all over my code. While refactoring I came across below code

data.map(function(d) {
   return {id: d.id, selected: bool};
});

我将上面的代码更改为此-

I changed above code to this -

data.map((d) => {id: d.id, selected: bool});

但是我从上面的代码中得到了错误.我不知道这是怎么回事? 我知道,如果没有代码块,则箭头功能会提供隐式返回.

But I was getting error from above code. I don't know what is wrong here? I know that If there is no block of code then there is implicit return provided by arrow function.

但是不知道如何返回已初始化某些属性的空对象或匿名对象?

But don't know how to return empty object or anonymous object with some properties initialized ?

如果以这种方式这样做有什么问题?只是出于好奇.

What is wrong if I do it in this way? Just for curiosity sake.

data.map((d) => new {id: d.id, selected: bool});

推荐答案

将对象初始值设定项周围的括号:

Put parens around the object initializer:

data.map((d) => ({id: d.id, selected: bool}) );

括号对它们内部的表达式的值没有影响,但是对它们的语法作用是消除所包含表达式的第一个标记的歧义.如果没有括号,JavaScript解析器必须确定{标记的含义是此处启动函数体"还是此处启动对象初始化器". 总是选择前者(即一段代码).

Parentheses have no effect on the value of the expression inside them, but they do have the syntactic effect of eliminating the ambiguity of the first token of the contained expression. Without the parentheses, the JavaScript parser has to decide whether the { token means "Here starts a function body" or "Here starts an object initializer." It always chooses the former (that is, a block of code).

因此,引入括号消除了混淆:前导(唯一可以表示的是表达式来了",因此{ inside 括号只能是这是一个对象初始化器." (换句话说,您不能将代码块放在表达式的中间;如果尝试,则会出现语法错误.)

Introducing the parentheses, therefore, eliminates the confusion: the only thing that a leading ( can mean is "here comes an expression", so that { inside the parentheses can only be "here comes an object initializer." (You can't drop a block of code in the middle of an expression, in other words; if you try, then you'll get a syntax error.)

这篇关于如何从JavaScript中的一个划线箭头函数返回匿名对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆