高阶函数javascript [英] higher order function javascripts

查看:64
本文介绍了高阶函数javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更好地理解并开始使用高阶函数编写JS.下面只是我正在做的一种练习,我想输出一个数字数组* 2.

I'm trying to understand better and start coding JS with higher order functions. Below is just a practice I'm doing, and I want to output an array of numbers * 2.

function each(collection, callback) {
  for(var i = 0; i < collection.length; i++) {
    callback(collection[i]);
    }
}

function isNumber(item) {

  var arr = [];
    if(typeof item === "number") {
      arr.push(item * 2);
    }

  return arr;
}

each([1, 2, 3, 4, "String"], isNumber);

据我了解,当使用array和isNumber参数调用each()函数时,它将遍历函数each.调用每个函数时,它会调用array [i]的isNumber函数,然后调用具有array [i]的isNumber函数,并且如果array [i]的类型是数字,则将该数字* 2推入一个大批.我期望的输出是

from my understanding, when each() function is invoked with array and isNumber argument, it runs through function each. When each function is invoked, it calls back isNumber function with array[i], then isNumber function with that array[i] is invoked and if the type of the array[i] is a number, it pushes that number * 2 to an array. The output I'm expecting is

[2, 4, 6, 8] since "String" is not a number it never got pushed into the array.

我不正确理解这一点吗?当我尝试记录此代码时,未显示任何输出.

Am I not understanding this correctly? When I try to log this code, no output shows.

推荐答案

我认为这对您有用:

// Let's call this what it is
function getNumbersFromArray(collection, callback) {
    var arr = [],
        i = 0;

    for (; i < collection.length; i++) {
        // Check if isNumber and do mutliplication here
        if (callback(collection[i])) {
            arr.push(item * 2);
        }
    }

    return arr;
}

// Make isNumber actually return a boolean
function isNumber(item) {
    return typeof item === "number";
}

// call console.log()
console.log(getNumbersFromArray([1, 2, 3, 4, "String"], isNumber)); 

这篇关于高阶函数javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆