简体   繁体   English

谁能向我解释此功能的工作原理?

[英]Could anyone explain to me how this function works?

Write a function capitals that takes a single string (word) as argument. 编写一个函数大写字母,以单个字符串(单词)作为参数。 The functions must return an ordered list containing the indexes of all capital letters in the string. 函数必须返回一个有序列表,其中包含字符串中所有大写字母的索引。

Example

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

My solution is this which is the simple for loop: 我的解决方案是以下这是简单的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;
}

But I want to understand this one using higher order function: 但是我想使用高阶函数来理解这一点:

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

especially the 'map(function(item, i)' part say why it knows i is the index without us defining it anywhere? 尤其是“ map(function(item,i)”部分)说出为什么它知道我是索引,而无需我们在任何地方定义它?

Thanks for your help! 谢谢你的帮助!

See code comments: 查看代码注释:

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; 
          });
}

For an explanation of map(), see this MDN page . 有关map()的说明,请参见此MDN页面 The function passed to map() is a callback which is taking three arguments - the element from an array over which map() is called, an index of this element in the array and an array itself. 传递给map()的函数是一个回调函数,它接受三个参数-调用map()的数组中的元素,该元素在数组中的索引以及数组本身。


Here's an example of map() itself. 这是map()本身的示例。 Consider this code: 考虑以下代码:

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);

It will print: 它将打印:

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']

Note that in this example we're using index parameter to capitalize only every other letter. 请注意,在此示例中,我们使用index参数仅将每隔一个字母大写一次。 Also note that map() would work with array of numbers, objects etc, not only letters. 还要注意, map()可以处理数字,对象等的数组,而不仅限于字母。

That's the beauty of map : you don't have to write your for loop, it's already in the body of the map function. 这就是map :您不必编写for循环,它已经在map函数的主体中。

The body of map contains a for loop which declares the index and "injects" it into the function you passed to it. map的主体包含一个for循环,该循环声明索引并将其“注入”到传递给它的函数中。

map applies a function to each element of the collection, in your case after split you have an array of chars, item is the current char and i is the index, the first operation: map对集合的每个元素应用一个函数,在您的情况下, split后您有一个char数组, item是当前char, i是索引,第一个操作:

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

Is applied to all chars and reads, if this char is upper case return the index, else return null (this syntax condition ? value : default is called ternary operator). 应用于所有字符并读取,如果此字符为大写则返回索引,否则返回null (此语法condition ? value : default称为三元运算符)。

The second is a filter to remove the null values from the array leaving only the indexes. 第二个是一个过滤器,用于从数组中删除空值,仅保留索引。

why it knows i is the index without us defining it anywhere? 为什么知道我是索引而无需在任何地方定义它?

It actually is defined, within the map function. 它实际上是在map函数中定义的。 For every item in the source array, it will provide three parameters to the callback function that you pass in. From MDN : 对于源数组中的每个项目,它将为您传入的callback函数提供三个参数。来自MDN

callback

Function that produces an element of the new Array, taking three arguments: 产生新Array元素的函数,带有三个参数:

  • currentValue
    The current element being processed in array. 当前元素正在数组中处理。
  • index
    The index of the current element being processed in array. 数组中正在处理的当前元素的索引。
  • array
    The array map was called upon. 调用了数组映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我不知道这个 function 是如何工作的。 谁能给我解释一下? - I don't know how this function works. Can anyone explain this to me? 谁能解释一下“ if(blnRtrn == true)”的工作原理吗? - Can anyone please explain me how this “if (blnRtrn == true)” works? 谁能解释以下代码的作用以及如何工作? - Could anyone please explain what the following code does and HOW it works? 谁能解释下面的代码块是如何工作的? - Could anyone explain how the below code block works? 有人可以向我解释这个功能是如何工作的吗? - Can someone explain to me how this function works? 任何人都可以向我解释我的代码中返回与警报功能之间的区别是什么 - Could anyone please explain to me what is the difference between return vs alert function in my code 有人可以向我解释如何将这种递归函数添加到自身中吗? - Can someone explain to me how adding this recursive function to itself works? 谁能告诉我这个 javaScript function 是如何工作的? - Can anyone tell me how this javaScript function works please? 有人可以用外行人的方式解释此功能的工作原理吗? - Could someone explain how this function works in laymans terms? 谁能解释这段代码是如何工作的? - Can anyone explain how this block of code works?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM