如何通过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
formalGreetingfunction doesn't return the new array thatmap()generates, so you'd never get the final result even if the callback was set up correctly. - The
nameparameter in your arrow function isn't being used properly; we need to access each individual element from thenamesarray inside themap()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
相关产品推荐
相关产品推荐

