2017-02-24 22 views
2

這個挑戰就是擊敗陣列時不定義任何新的功能:展平數組:0從哪裏來?

// challenge 
const arr = [1, [2]] 
const flattened = arr.reduce(/*your code here, no function expressions or declarations allowed*/, []) 
console.log(flattened) // expected: [1, 2] 

我的解決方法是不行的,但真正的錯誤我是,我不知道那裏的0是來自:

// Solution 1 
const arr = [1, [2]] 
const flattened = arr.reduce(Function.prototype.call.bind(Array.prototype.concat), []) 
console.log(flattened) // unexpected result: [1, 0, 1, [1], 2, 1, 1, [1]] 

我預料的代碼行爲像後續的,預期其工作原理:

// Solution 2 
const arr = [1, [2]] 
const flattenReducer = (x, y) => Function.prototype.call.bind(Array.prototype.concat)(x, y) 
const flattened = arr.reduce(flattenReducer, []) 
console.log(flattened) // logs the expected result: [1, 2] 

我的節點,Chrome和杉木測試efox並獲得了相同的結果。

那麼0來自何處?爲什麼解決方案1和解決方案2產生flattened的不同值?

回答

6

reduce的回調不僅有兩個參數。實際上它有四個:累加器,當前值,索引和原始數組。

您的解決方案#1相當於

arr.reduce(function (x, y, z, a) { 
    return Function.prototype.call.bind(Array.prototype.concat)(x, y, z, a); 
}, []); 

或等價

arr.reduce(function (x, y, z, a) { 
    return x.concat(y, z, a); 
}, []); 

這是不對的。

另請注意,您的兩個解決方案實際上並沒有將多於兩個維度的數組展平。

+0

現在我看到'0'來自哪裏,它來自索引 –

0

在這種情況下,不需要簡化將const簡化爲新的const或var。

const arr = [1, [2]]; 
var arrFlat = [].concat.apply([], arr); 
console.log(arrFlat); 

雖然想了解這個問題的颯爽你會更好的理解提供了基類方法本身,因爲他們已經建立,以幫助多餘的使用情況,而不需要的基本用法的學術部分用於大部分的耦合/嵌套/鏈接。

+0

他問爲什麼它輸出0 – Josh

+0

真實的,但是這不是代碼的挑戰:面臨的挑戰是在這裏填寫'/ *你的代碼... * /' –

+0

我想我對代碼挑戰的有用性及其實用用法或措辭有更多的印象。它說沒有函數可以使用,但用戶的第一個參數是對超類方法的調用。 如果我沒有在參數中聲明任何東西,並且只是將值賦給我的var,那麼我怎麼會出錯? –

2

.concat()是連接所有的參數在.reduce(function(a,b,index,array) {})