为什么箭头函数不返回值?

时间:2021-12-14 19:56:42

I have an arrow function that looks like this (simplified):

我有一个像这样的箭头函数(化简)

const f = arg => { arg.toUpperCase(); };

But when I call it, I get undefined:

但是当我调用它的时候,我没有定义

console.log(f("testing")); // undefined

Why?

为什么?

Example:

例子:

const f = arg => { arg.toUpperCase(); };
console.log(f("testing"));


(Note: This is meant to be a clean, canonical dupetarget for the specific issue with arrow functions above.)

(注意:这是一个干净的、规范的dupetarget针对上面的箭头函数的特定问题。)

1 个解决方案

#1


14  

When you use the function body version of an arrow function (with {}), there is no implied return. You have to specify it. When you use the concise body (no {}), the result of the body expression is implicitly returned by the function.

当您使用箭头函数的函数体版本(带有{})时,没有隐含的返回。你必须指定它。当您使用简洁的主体(没有{})时,该函数将隐式地返回body表达式的结果。

So you would write that either with an explicit return:

你可以用一个显式的返回来写:

const f = arg => { return arg.toUpperCase(); };
// Explicit return ^^^^^^

or with a concise body:

或以简洁的身体:

const f = arg => arg.toUpperCase();

Examples:

例子:

const f1 = arg => { return arg.toUpperCase(); };
console.log(f1("testing"));

const f2 = arg => arg.toUpperCase();
console.log(f2("testing"));


Slightly tangential, but speaking of {}: If you want the concise arrow's body expression to be an object initializer, put it in ():

稍微有点切分,但是说到{}:如果您想要简洁箭头的体表达式成为对象初始化器,请将其输入():

const f = arg => ({prop: arg.toUpperCase()});

#1


14  

When you use the function body version of an arrow function (with {}), there is no implied return. You have to specify it. When you use the concise body (no {}), the result of the body expression is implicitly returned by the function.

当您使用箭头函数的函数体版本(带有{})时,没有隐含的返回。你必须指定它。当您使用简洁的主体(没有{})时,该函数将隐式地返回body表达式的结果。

So you would write that either with an explicit return:

你可以用一个显式的返回来写:

const f = arg => { return arg.toUpperCase(); };
// Explicit return ^^^^^^

or with a concise body:

或以简洁的身体:

const f = arg => arg.toUpperCase();

Examples:

例子:

const f1 = arg => { return arg.toUpperCase(); };
console.log(f1("testing"));

const f2 = arg => arg.toUpperCase();
console.log(f2("testing"));


Slightly tangential, but speaking of {}: If you want the concise arrow's body expression to be an object initializer, put it in ():

稍微有点切分,但是说到{}:如果您想要简洁箭头的体表达式成为对象初始化器,请将其输入():

const f = arg => ({prop: arg.toUpperCase()});