【问题标题】:Why is this value undefined in the scope of reduce but defined in a for loop? (javascript)为什么这个值在 reduce 范围内未定义,但在 for 循环中定义? (javascript)
【发布时间】:2017-07-14 10:25:15
【问题描述】:

我正在尝试编写一个函数来查找一组数组中的唯一值...

function uniteUnique(arr) {
 var args = Array.prototype.slice.call(arguments);
  var result = [];

  for (var i=0; i<args.length; i++){
    console.log(args[i]);     // as expected this evaluates to [1, 3, 2]
                              // [5, 2, 1, 4]
                              // [2, 1]     

  }

  args.reduce(function(arg){
    console.log(arg + ' is the arg');  //for some reason arg is undefined
    arg.map(function(val){
      if (result.indexOf(val) < 0){
        result.push(val);

      }
      return result;
    });
  }, result);
}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

为什么上面在reduce中给了我undefined,但在for循环中却给了我一个有效值?是不是 reduce 函数只是隐式循环值(即产生 arg[0], arg[1], 等?)

编辑:这是我工作的解决方案...

function uniteUnique(arr) {
 var args = Array.prototype.slice.call(arguments);
  var result = [];

  args.reduce(function(acc, arg){
    console.log(arg + ' is the arg');  
    arg.map(function(val){
      if (result.indexOf(val) < 0){

        result.push(val);
        console.log(result + " is the current result");
      }
      return result;
    });
  }, result);
  return result;
}

【问题讨论】:

  • 您定义了args,但没有定义arg
  • @TimothyG。 arg 很好地定义为reduce 的回调参数。
  • 这看起来不像reduce 的用例。它看起来更像forEach
  • @ibrahimmahrir 不是 javascript 的大用户,所以我不知道。这只是一个健全性检查。
  • 你的代码中的问题是你没有从reduce的回调中返回任何东西来用作新的累加器(arg)。

标签: javascript arrays arguments reduce


【解决方案1】:

Mozilla Developer Network documentation可以给你很好的帮助。 reduce 的回调函数应该接收两个参数,累加器和您正在迭代的数组的当前值,所以我相信它应该看起来像这样:

function uniteUnique(arr) {
    var args = Array.prototype.slice.call(arguments);
    var result = [];
    var helper;
    for (var i=0; i<args.length; i++){
        console.log(args[i]); 
    }

    args.reduce(function(acc, arg){
    console.log(arg + ' is the arg');
    helper = arg.map(function(val){
      if (result.indexOf(val) < 0){
        result.push(val);
      }
      return result;
    });
    return acc + helper;
  }, result);
}

【讨论】:

  • 这段代码也不起作用,因为你没有解决代码中的大象问题:reduce 应该返回一些东西作为回调的第一个参数(下一个的累加器迭代)
  • @BrunoSantos 这看起来不错,但您似乎忘记定义 acc
  • @ibrahimmahrir 你是完全正确的,我已经修复了,要编辑答案
  • @DavidJ。问题是我以错误的方式工作。我已经确定了答案,但我看到你必须这样做,干得好!
猜你喜欢
  • 1970-01-01
  • 2015-12-16
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 2017-02-12
相关资源
最近更新 更多