如何从作为参数传入的嵌套函数中访问参数

时间:2016-02-24 21:15:36

标签: javascript function

我使用函数作为参数来构建reduce方法。如果传入的函数没有参数,那么我想返回0。

_.reduce = function(arr, fun){
    if(fun[0] == undefined){
        return 0;
    }
.
.

问题是即使将参数传递给fun,if语句也会执行。我是否试图错误地访问参数?

2 个答案:

答案 0 :(得分:2)

如果你想知道一个函数需要多少个参数,你应该check it's length

_.reduce = function(arr, fun) {
  if (!fun || !fun.length) {
    return 0;
  }
  ...
};

答案 1 :(得分:0)

考虑到您的功能“fun”始终定义,您可以根据此链接使用.length: gtk's io_add_watch()

_.reduce = function(arr, fun){
if(fun.length == 0){
    return 0;
}