谁能解释一下这个功能是如何工作的?

时间:2014-08-11 18:23:04

标签: javascript higher-order-functions

编写一个函数大写,它将一个字符串(单词)作为参数。函数必须返回一个有序列表,其中包含字符串中所有大写字母的索引。

实施例

Test.assertSimilar( capitals('CodEWaRs'), [0,3,4,6] );

我的解决方案就是这个简单的for循环:

function capitals(word) {
    var ara = [];
    for(var i = 0; i < word.length; i++){
        if(word[i] == word[i].toUpperCase()){
            ara.push(i)
        }
    }
    return ara;
}

但是我想用更高阶函数来理解这个:

function capitals(word) {
    return word.split('').map(function(item, i) {
        return item == item.toUpperCase() ? i : null;
    }).filter(function(x) {
        return x != null;
    });
}

尤其是&#39;地图(功能(项目,我)&#39;部分说明为什么它知道我是指数而没有我们在任何地方定义它?

感谢您的帮助!

4 个答案:

答案 0 :(得分:2)

参见代码注释:

function capitals(word) {
  return word
          .split('')  // split a word in an array of letters
          .map(function(item, i) {
              // if letter is an upper case, return its index, null otherwise
              return item == item.toUpperCase() ? i : null;
          }).filter(function(x) {
              // filter out all null elements, effectively leaving only
              // indices of uppercase letters in a string.
              return x != null; 
          });
}

有关map(), see this MDN page的解释。传递给map()的函数是一个回调,它带有三个参数 - 调用map()的数组中的元素,数组中此元素的索引以及数组本身。


以下是map()本身的示例。请考虑以下代码:

var result = ['a', 'b', 'c', 'd'].map(function(element, index) {
  console.log('element ' + element + ' is at position: ' + index);
  return index % 2 === 0 ? element.toUpperCase() : element;
});

console.log(result);

它将打印:

element a is at position: 0
element b is at position: 1
element c is at position: 2
element d is at position: 3 
['A', 'b', 'C', 'd']

请注意,在此示例中,我们使用index参数来仅大写每个其他字母。另请注意,map()可用于数组,对象等数组,而不仅仅是字母。

答案 1 :(得分:1)

这是map的美丽:你不必写for循环,它已经在map的正文中功能。

map的主体包含一个for循环,用于声明索引和&#34;注入&#34;它进入你传递给它的功能。

答案 2 :(得分:1)

map将一个函数应用于集合的每个元素,在split之后你有一个字符数组,item是当前字符,而i是索引,第一个操作:

return item == item.toUpperCase() ? i : null;

应用于所有字符和读取,如果此字符为大写,则返回索引,否则返回null(此语法condition ? value : default称为三元运算符)。

第二个是过滤器,用于从数组中删除空值,只留下索引。

答案 3 :(得分:1)

  

为什么它知道我是没有我们在任何地方定义它的索引?

实际上是在map函数中定义的。对于源数组中的每个项目,它将为您传入的callback函数提供三个参数。来自MDN

  

callback

     

生成新数组元素的函数,带有三个参数:

     
      
  • currentValue
      当前元素在数组中处理。
  •   
  • index
      在数组中处理的当前元素的索引。
  •   
  • array
      调用了数组映射。
  •   
相关问题