我做了一些涉及使用.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:06
.map()接受函数作为参数。在您的例子中,您正在传递一个匿名箭头函数。您的匿名箭头函数有一个可接受的名为firstLetter的参数。当您调用.map()时,它将对数组中的每个元素执行箭头函数,从而将此元素传递到函数中。
因此,firstLetter实际上并不表示firstLetter,而是表示数组中的给定元素。如果您将此参数重命名为更具代表性的名称,可能会更清楚:
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
const secretMessage = animals.map(animalType => {
return animalType[0]; // get the first character from a given string
});因此,执行上面的animalType[0]操作将得到给定字符串的第一个字符,而不是animals数组中的第一个元素。
https://stackoverflow.com/questions/56772571
复制相似问题