gpt4 book ai didi

javascript - JS : Using 'return' in arrow function syntax

转载 作者:行者123 更新时间:2023-11-30 11:30:33 24 4
gpt4 key购买 nike

我目前正在尝试返回 animals 数组中每个字符串的第一个字符,并使用 shorthand arrow function< 将其存储在名为 secretMessage 的新数组中/em> 语法。但是,我遇到了以下错误。

错误

/home/ccuser/workspace/learn-javascript-iterators-E3/main.js:5
secretMessage.map(animal => return animal[0]);
^^^^^^
SyntaxError: Unexpected token return

Js

let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

secretMessage.map(animal => return animal[0]);

console.log(secretMessage.join(''));

为什么会出现这种情况?以及如何解决此错误?

最佳答案

arrow function 中的表达式是返回值。

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

您可以删除单词 return

var secretMessage = animals.map(animal => animal[0]);

关于javascript - JS : Using 'return' in arrow function syntax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com