development

객체를 반환하는 ECMAScript 6 화살표 함수

big-blog 2020. 10. 3. 11:21
반응형

객체를 반환하는 ECMAScript 6 화살표 함수


화살표 함수에서 객체를 반환 할 때 문법의 모호함으로 인해 추가 {}return키워드 집합을 사용해야하는 것 같습니다 .

그 말은 내가 쓸 수 없습니다 p => {foo: "bar"}만 작성해야합니다 p => { return {foo: "bar"}; }.

화살표 기능은 객체 이외의 아무것도 반환하는 경우 {}와는 return, 예를 들어 불필요한 있습니다 p => "foo".

p => {foo: "bar"}를 반환합니다 undefined.

수정 A는 p => {"foo": "bar"}발생 " SyntaxError: 예기치 않은 토큰 ' :'" .

내가 놓친 명백한 것이 있습니까?


반환 객체 리터럴을 괄호로 묶어야합니다. 그렇지 않으면 중괄호가 함수의 본문을 나타내는 것으로 간주됩니다. 다음 작업 :

p => ({ foo: 'bar' });

다른 표현식을 괄호로 묶을 필요가 없습니다.

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

등등.

참조 : MDN-객체 리터럴 반환


구문이 유효하지만 예상대로 작동하지 않는 이유가 궁금 할 수 있습니다.

var func = p => { foo: "bar" }

JavaScript의 레이블 구문 때문입니다 .

따라서 위 코드를 ES5로 트랜스 파일하면 다음과 같이 보일 것입니다.

var func = function (p) {
  foo:
  "bar"; //obviously no return here!
}

화살표 함수의 본문이 중괄호로 묶여 있으면 암시 적으로 반환되지 않습니다. 개체를 괄호로 묶습니다. 다음과 같이 보일 것입니다.

p => ({ foo: 'bar' })

본문을 괄호로 감싸면 함수는를 반환 { foo: 'bar }합니다.

바라건대 문제가 해결되기를 바랍니다. 그렇지 않다면 최근에 더 자세히 다루는 Arrow 기능에 대한 기사를 썼습니다. 도움이 되셨기를 바랍니다. Javascript Arrow 함수


올바른 방법

  1. 일반 반환 객체

const getUser = user => {return { name: user.name, age: user.age };};

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

  1. (js 표현식)

const getUser = user => ({ name: user.name, age: user.age });

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

설명

image

The same answer can be found here!

https://github.com/lydiahallie/javascript-questions/issues/220

https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript


Issue:

When you do are doing:

p => {foo: "bar"}

JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.

Solution:

If your arrow function expression has a single statement, then you can use the following syntax:

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

But if you want to have multiple statements then you can use the following syntax:

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

For more details, check Mozilla Docs for JS Arrow Function Expressions


You can always check this out for more custom solutions:

x => ({}[x.name] = x);

참고URL : https://stackoverflow.com/questions/28770415/ecmascript-6-arrow-function-that-returns-an-object

반응형