我试图写一个函数来查找组阵列的唯一值...为什么这个值在reduce的范围中未定义,但在for循环中定义? (JavaScript)的
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]);
为什么上面给我undefined
在减少而是在for循环的有效值?不减少功能只是含蓄地遍历值(即生产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'! –