创建一个撰写函数javascript [英] Create a compose function javascript

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

问题描述

我需要一个组成其他函数的函数以及一个值参数。例如:

I would need a function that composes other function as well as taking a value parameter. For example:

var doubleTheValue = function(val) { return val * 2; }
var addOneToTheValue = function(val) { return val + 1; }
compose(5, doubleTheValue, addOneToTheValue)-> 11



最重要的是它必须接受任意数量的功能



我尝试了什么:



我知道可以在某处找到解决方案网络,但我来得非常接近我只是不明白我做的错误


The most important thing is that it has to accept any number of functions

What I have tried:

I know that might be possible to find a solution somewhere on the web but I came very close I just don`t understand the mistake I had made

function compose(val, fn, fn1) {
var args = [].slice.call(arguments);
  
  for(var i = args.length - 1; i > 0; i--){
    var a = args[i].call(this, args[0])
  }
 return a
}
compose(5, doubleTheValue, addOneToTheValue) -> 10



出于某种原因,它会忽略第一种方法产生10,为什么?


For some reason it produces 10 ignoring the first method, why?

推荐答案

这里有两个明显的问题:



1)你总是传递 val 到组合函数,忽略从前一个组合函数返回的值。



2)你以相反的顺序调用组合函数:(5 + 1)* 2 而不是(5 * 2)+ 1



所以你的代码相当于:

Two obvious problems here:

1) You're always passing val to the composed functions, ignoring the value returned from the previous composed function.

2) You're calling the composed functions in reverse order: (5 + 1) * 2 instead of (5 * 2) + 1.

So your code is equivalent to:
val = 5;
a = addOneToTheValue(val); // = 6
a = doubleTheValue(val);   // = 10
return a;



而不是:


instead of:

val = 5;
a = val; // = 5
a = doubleTheValue(a);   // = 10
a = addOneToTheValue(a); // = 11
return a;





尝试这样的事情:



Try something like this:

function compose(val){
    var result = val;
    
    for (var i = 1; i < arguments.length; i++){
        result = arguments[i].call(this, result);
    }
    
    return result;
}

compose(5, doubleTheValue, addOneToTheValue); -> 11


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

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