2017-02-24 35 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) {})