Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

javascript - 返回对象的ECMAScript 6箭头函数(ECMAScript 6 arrow function that returns an object)

When returning an object from an arrow function, it seems that it is necessary to use an extra set of {} and a return keyword because of an ambiguity in the grammar.(从箭头函数返回对象时,由于语法上的歧义,似乎有必要使用额外的{}return关键字。)

That means I can't write p => {foo: "bar"} , but have to write p => { return {foo: "bar"}; }(这意味着我不能写p => {foo: "bar"} ,而必须写p => { return {foo: "bar"}; }) p => { return {foo: "bar"}; } .(p => { return {foo: "bar"}; } 。) If the arrow function returns anything other than an object, the {} and return are unnecessary, eg: p => "foo" .(如果arrow函数返回的不是对象,则{}return都是不必要的,例如: p => "foo" 。) p => {foo: "bar"} returns undefined .(p => {foo: "bar"}返回undefined 。) A modified p => {"foo": "bar"} throws SyntaxError : unexpected token: ' : '” .(修改后的p => {"foo": "bar"}抛出SyntaxError :意外令牌:' : '” 。) Is there something obvious I am missing?(有什么明显的我想念的东西吗?)   ask by jkschneider translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must wrap the returning object literal into parentheses.(您必须将返回的对象文字包装在括号中。)

Otherwise curly braces will be considered to denote the function's body.(否则,花括号将被视为表示功能的主体。) The following works:(以下作品:) p => ({ foo: 'bar' }); You don't need to wrap any other expression into parentheses:(您不需要将任何其他表达式包装到括号中:) p => 10; p => 'foo'; p => true; p => [1,2,3]; p => null; p => /^foo$/; and so on.(等等。) Reference: MDN - Returning object literals(参考: MDN-返回对象文字)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...