2017-04-04 69 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 ]