You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过ES6使用map()函数?代码问题咨询

Fixing Your ES6 map() Usage

Hey there! Let's break down what's off with your current code and get it working right with ES6 map().

First, let's spot the issues in your original code:

  • map() requires a callback function as its argument, but you passed a string ("Hello " + name) directly — that's why it won't run as expected.
  • Your formalGreeting function doesn't return the new array that map() generates, so you'd never get the final result even if the callback was set up correctly.
  • The name parameter in your arrow function isn't being used properly; we need to access each individual element from the names array inside the map() callback.

Here's the corrected version

const names = ["Will", "Rick", "Blake"];
const formalGreeting = () => {
  // map() uses a callback that receives each array element as an argument
  return names.map(name => `Hello ${name}`);
};

// Test it out!
console.log(formalGreeting()); // Output: ["Hello Will", "Hello Rick", "Hello Blake"]

Even more concise (ES6 shorthand)

Since arrow functions let us omit curly braces and return when there's only one expression, we can simplify this further:

const names = ["Will", "Rick", "Blake"];
const formalGreeting = () => names.map(name => `Hello ${name}`);

A quick reminder about map(): It creates and returns a new array by applying your callback to every element in the original array. It never modifies the original array, which is great for keeping your data immutable (a common ES6 best practice).

内容的提问来源于stack exchange,提问作者PBandJ333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:29:32