2017-04-04 63 views
-1

即时工作的练习中,从一个数组数组开始,我必须在包含给定每个单个数组的所有元素的单个数组中减少它(使用reduce和concat)。Javascript:练习concat并减少

所以我从这个开始:

var array = [[1,2,3],[4,5,6],[7,8,9]] 

而且我解决了这个锻炼; Tibial:

var new_array = array.reduce(function(prev,cur){return prev.concat(cur);}) 

所以它的工作原理,打字的console.log(new_array)我有这样的:

[1, 2, 3, 4, 5, 6, 7, 8, 9] 

但是,如果我以这种方式修改功能:

var new_array = array.reduce(function(prev,cur){return prev.concat(cur);},0) 

我得到这个错误:

"TypeError: prev.concat is not a function 

为什么我得到这个错误?在此先感谢

+0

因为你不能连接数组到0 –

+0

第二个(和选择nal)'Array.prototype.reduce'的参数是初始值。在你的情况下,你传递'0'作为初始值,因此函数首次运行时会尝试调用'prev.concat',因为'Number'没有'concat'方法,显然会失败。 – haim770

+0

你试图用第二个版本的reduce来实现什么? – Harald

回答

1

i not have completely clear how reduce works yet

它的工作原理是这样的:

Array.prototype.reduce = function(callback, startValue){ 
    var initialized = arguments.length > 1, 
     accumulatedValue = startValue; 

    for(var i=0; i<this.length; ++i){ 
     if(i in this){ 
      if(initialized){ 
       accumulatedValue = callback(accumulatedValue, this[i], i, this); 
      }else{ 
       initialized = true; 
       accumulatedValue = this[i]; 
      } 
     } 
    } 

    if(!initialized) 
     throw new TypeError("reduce of empty array with no initial value"); 
    return accumulatedValue; 
} 

发生故障的例子确实相当多这样的:

var array = [[1,2,3],[4,5,6],[7,8,9]]; 

var tmp = 0; 
//and that's where it fails. 
//because `tmp` is 0 and 0 has no `concat` method 
tmp = tmp.concat(array[0]); 
tmp = tmp.concat(array[1]); 
tmp = tmp.concat(array[2]); 

var new_array = tmp; 

更换0使用数组一样[ 0 ]