【发布时间】: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