2017-02-23 74 views
2

我试图写一个函数来查找组阵列的唯一值...为什么这个值在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; 
} 
+0

你'args'定义但未' arg'? –

+0

@TimothyG。 'arg'被明确定义为'reduce'回调的参数。 –

+1

这看起来不像'reduce'的用例。它看起来更像'forEach'! –

回答

2

Mozilla Developer Network documentation可以给你一个很好的帮助。的减少回调函数应接受两个参数,累加器和你遍历数组的电流值,所以我相信它应该是这个样子:

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); 
} 
+1

其他参考资料[在W3](https://www.w3schools.com/jsref/jsref_reduce.asp) –

+0

这段代码不会工作,因为你没有给大象在代码中:** reduce应该返回一些用作回调的第一个参数(下一次迭代的累加器)**! –

+0

@BrunoSantos这看起来不错,但它看起来像你忘了定义'acc' –

相关问题