查找数组中每个元素的首字母

时间:2019-06-26 12:14:12

标签: javascript

我正在做一些涉及使用.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处的项?

6 个答案:

答案 0 :(得分:1)

map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的function。例如:

  • 迭代1 firstLetter = 'Hen',所以'Hen'[0] = 'H'
  • 迭代2 firstLetter = 'elephant',所以'elephant'[0] = 'e'。 等等...

以下是文档:map

答案 1 :(得分:1)

map()遍历数组,复制每个值并进行转换,并将每个转换结果写入新数组。在每个迭代步骤中,它都将当前值视为firstLetter,并使用其作为参数(firstLetter)调用一个函数。因此,firstLetter依次是Hen,然后是elephant,依此类推。在每个变量上应用函数,该函数返回参数的第一个字母,然后将其放入新数组中。

以下命名应更清楚我的意思:

const secretMessage = animals.map(currentValue => {
  return currentValue[0]
});

答案 2 :(得分:0)

.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数组中的第一个元素。

答案 3 :(得分:0)

使用Destructuring assignment

取第一个字母

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


const result = animals.map(([v])=> v);
console.log(result);

答案 4 :(得分:0)

如评论中所述,map函数遍历数组中的每个元素。当您访问firstLetter[0]时,您不是在访问数组animals的第一个元素,而是在访问字符串firstLetter的第一个字符。

map的工作方式是遍历列表中的每个元素并对其执行某些功能,因此代码如下:

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

const secretMessage = animals.map(firstLetter => {
  return firstLetter[0]
});

等同于

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

let secretMessage = [];
for (var i = 0; i < animals.length; i++) {
  firstLetter = animals[i] # the ith string in animals
  secretMessage.push(firstLetter[0]) # add the first letter of the string
}

map函数采用一个以元素为参数的函数,并创建该函数返回值的数组,其中包含数组中的每个元素。因此,对于'Hen',函数firstLetter => firstLetter[0]返回'H',然后对于'elephant',它是'e',依此类推。然后,将secretMessage设置为['H', 'e', ...]

答案 5 :(得分:0)

Map对数组中的每个值进行迭代。 因此,假设第一个的firstLetter指向'Hen',因此firstLetter[0]等于H,依此类推,对于数组中的所有其他值。