我做了一些涉及使用.map()的练习,这一切看起来都很简单。但是,在其中一个示例中,我的任务是使用.map()迭代器返回数组中每一项的第一个字母。
请看下面解决问题的代码。
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
const secretMessage = animals.map(firstLetter => {
return firstLetter[0]
});
console.log(secretMessage)
我的问题是,firstLetter()函数如何知道只返回动物数组中每个字符串的第一个字母,而不是重复返回索引为0的项?
发布于 2019-06-26 20:20:10
map()遍历您的数组,复制每个值并对其进行转换,将每个转换结果写入一个新的数组。在每个迭代步骤中,它将当前值视为firstLetter,并使用该值作为参数(firstLetter)调用函数。因此,firstLetter依次是Hen,然后是elephant,等等。在每个数组上,您都可以应用函数,该函数返回参数的第一个字母,然后将其放入新的数组中。
下面的命名应该更清楚地说明我的意思:
const secretMessage = animals.map(currentValue => {
return currentValue[0]
});https://stackoverflow.com/questions/56772571
复制相似问题