为什么我的箭头函数没有返回值? [英] Why doesn't my arrow function return a value?

查看:132
本文介绍了为什么我的箭头函数没有返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

但是当我调用它时,我得到 undefined

But when I call it, I get undefined:

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

为什么?

示例:

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

注意:这是一个干净的,规范的dupetarget,用于上面箭头函数的特定问题。)

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

推荐答案

当您使用箭头功能的函数体版本时(使用 {} ),没有隐含的返回。你必须指定它。当您使用简洁正文(没有 {} )时,函数会隐式返回正文表达式的结果。

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.

所以你要写一个明确的返回

So you would write that either with an explicit return:

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

或简洁的机构:

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

示例:

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

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

稍微切线,但说到 {} :如果你想要简明扼要arrow的body表达式是一个对象初始值设定项,把它放在()

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()});

这篇关于为什么我的箭头函数没有返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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