简体   繁体   English

有人可以向我解释函数中的一行代码吗

[英]Can someone explain me a line of code in a function

Could someone please explain me what does this line of code actually means step by step.有人可以解释我这行代码实际上是什么意思一步一步。

arrRes.push(fn(arr[i]));

I understand the push part but I am struggling to grasp the code in the parenthesis.我理解推送部分,但我很难掌握括号中的代码。

The whole function looks like this :整个函数如下所示:

function arrayCalc (arr, fn) {

    arrRes = [];

    for (let i = 0; i < arr.length; i++) {

        arrRes.push(fn(arr[i])); // <--- this line here in the parenthesis

    }
    return arrRes;
};

Sorry if this is a dumb question but I've watched the tutorial video for five times and I just can't understand what that line exactly means.对不起,如果这是一个愚蠢的问题,但我已经观看了五次教程视频,我只是无法理解该行的确切含义。

Thanks!谢谢!

there is some function fn passed as argument and array arr有一些函数fn作为参数和数组arr传递

arrRes.push(fn(arr[i])); - means: - 方法:

  1. take value from arr (index is i )arr取值(索引为i
  2. execute function fn with value as a parameter作为参数执行函数fn
  3. whatever is result, push it to arrRes无论结果如何,将其推送到arrRes

example例子

 function arrayCalc (arr, fn) { arrRes = []; for (let i = 0; i < arr.length; i++) { arrRes.push(fn(arr[i])); } return arrRes; }; const someArr = [1,2,3]; function someFunction(number) { return number * 10; } function someOtherFunction(number) { return `${number}_Z`; } console.log(arrayCalc(someArr, someFunction)) // [10, 20, 30] console.log(arrayCalc(someArr, someOtherFunction)) // ['1_Z', '2_Z', '3_Z']

This is usually called a mapping: apply a function to each element of a collection... Thus if you have an array [1,2,3] and map it with a function that multiplies a number by 2, you will end with an array equals to [2,4,6].这通常称为映射:将函数应用于集合的每个元素...因此,如果您有一个数组 [1,2,3] 并将其映射到一个将数字乘以 2 的函数,您将以数组等于 [2,4,6]。

To compute it, you need an array, arr and a function fn .要计算它,您需要一个数组arr和一个函数fn Then for each element of arr in turn you apply fn to it and place the result at the end of the new collection.然后依次对arr每个元素应用fn并将结果放在新集合的末尾。 You can write it as:你可以把它写成:

arrRes = [];
for (let i = 0; i < arr.length; i++) {
    var dummy = arr[i]; 
    var mapped = fn(dummy);
    arrRes.push(mapped);
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM